|
Can I append the content of a struct that's serializable via the NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE macro to a json object? I would expect the output to be: The documentation doesn't make it clear how something like that would work. |
Replies: 2 comments
|
If you really want those added directly to the existing object like that, you would need to call The |
|
What you want is a merge — testJson["A"] = "A";
testJson["B"] = "B";
TestStruct myStruct;
testJson.update(nlohmann::json(myStruct));Result: {
"A": "A",
"B": "B",
"field1": 5,
"field2": 10,
"someStr": "Abcd",
"myArray": [0, 0, 0, 0, 0]
}
@gregmarr's (Side note: |
push_back(myStruct)does not merge object fields. Once you've donetestJson["A"] = "A", the json value is an object, and pushing a plain value into an object is not the operation you want; it throws atype_error.+=fails for the same reason.What you want is a merge —
update()does exactly this:Result:
{ "A": "A", "B": "B", "field1": 5, "field2": 10, "someStr": "Abcd", "myArray": [0, 0, 0, 0, 0] }update(const json&)constructs a temporaryjsonfrommyStructvia theto_jsonproduced by yourNLOHMANN_DEFINE_TYPE_NON_INTRUSIVEmacro, then folds its keys into t…