-
-
Notifications
You must be signed in to change notification settings - Fork 6.7k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
How to Serialize derived class to JSON object? #2199
Labels
kind: question
solution: proposed fix
a fix for the issue has been proposed and waits for confirmation
Milestone
Comments
heartfly
changed the title
How to serialize subclasses to JSON object?
How to derived class to JSON object?
Jun 18, 2020
This should work: #include <iostream>
#include "json.hpp"
using json = nlohmann::json;
struct A {
double Aa;
double Ab;
};
struct B : public A{
int Ba;
int Bb;
};
void to_json( nlohmann::json& JSON, const A& a ) {
JSON = { {"Aa", a.Aa}, {"Ab", a.Ab} };
}
void to_json( nlohmann::json& JSON, const B& b ) {
nlohmann::to_json(JSON, static_cast<A>(b));
JSON.update({ {"Ba", b.Ba}, {"Bb", b.Bb} });
}
int main() {
A a;
a.Aa = 1.11;
a.Ab = 2.22;
B b;
b.Aa = 1.1;
b.Ab = 2.2;
b.Ba = 3;
b.Bb = 4;
json ja = a;
std::cout << ja << std::endl;
json jb = b;
std::cout << jb << std::endl;
} Output: {"Aa":1.11,"Ab":2.22}
{"Aa":1.1,"Ab":2.2,"Ba":3,"Bb":4} |
nlohmann
added
the
solution: proposed fix
a fix for the issue has been proposed and waits for confirmation
label
Jun 18, 2020
thx.
but got an error
|
heartfly
changed the title
How to derived class to JSON object?
How to Serialize derived class to JSON object?
Jun 18, 2020
The error message gives a hint:
Changing the second argument to a reference works: void from_json( const nlohmann::json& JSON, B& b ) {
nlohmann::from_json(JSON, static_cast<A&>(b));
JSON.at("Ba").get_to(b.Ba);
JSON.at("Bb").get_to(b.Bb);
} |
It works! thank you @nlohmann |
4 tasks
4 tasks
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Labels
kind: question
solution: proposed fix
a fix for the issue has been proposed and waits for confirmation
What do you want to achieve?
I'm trying to serialize my objects. They look like this (overly simplified):
What have you tried?
I'm trying to create a JSON object like this:
Can you provide a small code example?
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.
The text was updated successfully, but these errors were encountered: