-
-
Notifications
You must be signed in to change notification settings - Fork 6.9k
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
[question] to_json for base and derived class #803
Comments
You write "does not work" - what does it do and what did you expect instead? |
ok, #include <iostream>
#include <fstream>
#include <string>
#include "json.h"
using namespace std;
class A
{
public:
A() : m_aa("aa"), m_ab("ab"), m_ac("ac") {};
virtual ~A() {};
private:
string m_aa;
string m_ab;
string m_ac;
friend void to_json(nlohmann::json& j,const A e);
};
void to_json(nlohmann::json& j,const A e)
{
j = nlohmann::json{
{"m_aa", e.m_aa},
{"m_ab", e.m_ab},
{"m_ac", e.m_ac},
};
}
class B : public A
{
public:
B() : m_ba("ba"), m_bb("bb") {};
virtual ~B() {};
private:
string m_ba;
string m_bb;
friend void to_json(nlohmann::json& j,const B e);
};
void to_json(nlohmann::json& j,const B e)
{
j = nlohmann::json{
static_cast<A>(e),
{"m_ba", e.m_ba},
{"m_bb", e.m_bb},
};
}
int main()
{
cout << "Hello world!" << endl;
B b;
nlohmann::json j = b;
//addCDKSwindow(console,j.dump(4).c_str(),TOP);
std::ofstream file;
file.open("tmp_file.txt");
file << j.dump(4);
file.close();
return 0;
} the output i get is [
{
"m_aa": "aa",
"m_ab": "ab",
"m_ac": "ac"
},
[
"m_ba",
"ba"
],
[
"m_bb",
"bb"
]
] expected: {
"m_aa": "aa",
"m_ab": "ab",
"m_ac": "ac",
"m_ba": "ba",
"m_bb": "bb"
} |
i know this probably can not work with my approach, but i would like to know how i can do this without some complicated construct... |
The problem is j = nlohmann::json{
static_cast<A>(e),
{"m_ba", e.m_ba},
{"m_bb", e.m_bb},
}; The initialization list is only treated as an object if each element is a pair whose first element is a string, like j = nlohmann::json{
{"m_aa", e.m_aa},
{"m_ab", e.m_ab},
{"m_ac", e.m_ac},
}; If this is not the case, the result is an array just as you experienced it. Instead, use the j = static_cast<A>(e);
j["m_ba"] = e.m_ba;
j["m_bb"] = e.m_bb; |
facepalm |
No worries! |
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:
i would like to have a resulting json element like this
with the provided code this does not work... Any idea?
The text was updated successfully, but these errors were encountered: