json_struct
json_struct copied to clipboard
Missing support to add Map value in a Map with key name
static void from(const fromCustomType&, Token& token, Serializer& serializer) {
Map nestedMap;
JS::ParseContext parseContext;
nestedMap.setValue("innerKey1", parseContext, "value1");
nestedMap.setValue("innerKey2", parseContext, 42);
Map outerMap;
outerMap.setValue("regularKey", parseContext, "simpleValue");
outerMap.setValue("mapKey", parseContext, nestedMap);
TypeHandler<Map>::from(outerMap, token, serializer);
}
The following code produces the below json
{"regularKey":[115,105,109,112,108,101,86,97,108,117,101,0],{"innerKey1":[118,97,108,117,101,49,0],"innerKey2":42}}
Adding this in TypeHandler<Map> from method fixes the issue
static inline void from(const Map &from_type, Token &token, Serializer &serializer) { bool isNamedValue = token.name.data != nullptr; if (!isNamedValue) { for (auto &token : from_type.tokens.data) { serializer.write(token); } return; }
Token nameToken;
nameToken.name_type = token.name_type;
nameToken.name = token.name;
nameToken.value_type = Type::ObjectStart;
nameToken.value = DataRef("{");
serializer.write(nameToken);
// Write the Map's inner content (skip the outer object braces)
if (from_type.tokens.data.size() >= 2 &&
from_type.tokens.data[0].value_type == Type::ObjectStart &&
from_type.tokens.data.back().value_type == Type::ObjectEnd) {
// Write only the inner tokens (between outer braces)
for (size_t i = 1; i < from_type.tokens.data.size() - 1; ++i) {
serializer.write(from_type.tokens.data[i]);
}
}
// Close the nested object
Token endToken;
endToken.value_type = Type::ObjectEnd;
endToken.value = DataRef("}");
serializer.write(endToken);
}
I would be happy to create a Pull Request for the fix. Let me know if I can do that.
Hey, I just pushed your fix with some slight modifications, and a test. Can you please verify that this is inline with what you had in mind.
https://github.com/jorgen/json_struct/commit/439fb62a87f3acd880b909f68fe0122c38df9b7e
Thanks, yeah the changes look good and work correctly for the scenario that I shared.