Skip to content

How to Serialize derived class to JSON object?  #2199

Closed
@heartfly

Description

@heartfly

What do you want to achieve?

I'm trying to serialize my objects. They look like this (overly simplified):

class A {
 double Aa;
 double Ab;
};

class B : public A{
  int Ba;
  int Bb;
};

What have you tried?

I'm trying to create a JSON object like this:

B = {
 "Aa": 1.0,
 "Ab": 2.0,
 "Ba": 3,
 "Bb": 4
}

Can you provide a small code example?

inline void to_json( nlohmann::json& JSON, const A& a ) {
  JSON = { "Aa", a.Aa, "Ab", a.Ab };
}
inline void to_json( nlohmann::json& JSON, const B& b ) {
 // how to call the base class(A)'s to_json and from_json function?
  JSON = { "Ba", b.Ba, "Bb", b.Bb };
}

Please help me know how to call the base class's to_json and from_json function.

Describe which system (OS, compiler) you are using.
LLVM 3.8.1

Describe which version of the library you are using (release version, develop branch).
Fairly recent from master branch.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions