Skip to content

[question] to_json for base and derived class #803

Description

@bluehazzard

Hi,
this is not a bug report but a question. I have a base class and a derived class, both with some members. Now i would like to store them in a json object:

class A
{
   private:
    std::string m_base;
}

class B : public A
{
   private:
     std::string m_derived;
}

void to_json(nlohmann::json& j,const A el)
{
   j = nlohmann::json{
      {"base", el.m_base},
   }
}

void to_json(nlohmann::json& j,const B el)
{
   j = nlohmann::json{
     static_cast<A>(el),   // insert the "base" element
     {"derived", el.m_derived}
   }
}

i would like to have a resulting json element like this

{
  "base" : "content base",
  "derived" : "content derived"
}

with the provided code this does not work... Any idea?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    solution: proposed fixa fix for the issue has been proposed and waits for confirmation

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions