-
-
Notifications
You must be signed in to change notification settings - Fork 7.3k
Description
Hi Nils,
Is it possible to add a state based serialization interface, where I can use the same interface of writing values independent whether it is an array or a normal json based value?
The current problem I have is a code duplication because of the current interface:
bool write_atomic_types_to_json(nlohmann::json& j, std::string name, const variant& var, const type& t)
{
if (t.is_arithmetic())
{
if (t == type::get<bool>())
j[name] = var.to_bool();
else if (t == type::get<char>())
j[name] = var.to_bool();
else if (t == type::get<int8_t>())
j[name] = var.to_int8();
else if (t == type::get<int16_t>())
j[name] = var.to_int16();
//.... more code to follow
return true;
}When I do now the same for an array, I cannot reuse the code from above, I have to use push_back, to insert the values.
bool write_atomic_types_to_json_array(nlohmann::json& j, const variant& var, const type& t)
{
if (t.is_arithmetic())
{
if (t == type::get<bool>())
j.push_back(var.to_bool());
else if (t == type::get<char>())
j.push_back(var.to_bool());
else if (t == type::get<int8_t>())
j.push_back(var.to_int8());
else if (t == type::get<int16_t>())
j.push_back(var.to_int16());
//... more code to follow
return true;
}There are two different interfaces for writing a value in JSON, this is okay. But for my use case
it would be nice to have something like this:
writer.StartObject();
writer.String("Foo");
writer.Int(42);
writer.String("MyArray");
writer.StartArray();
writer.Int(1);
writer.Int(2);
writer.Int(3);
writer.EndArray();
writer.EndObject();Will result in following:
{
"Foo" : 42,
"MyArray" : [1, 2, 3]
}That code snippet is actually from rapid-json.
You see the writing of key and the value doesn't distinguish between an array or a normal key-value based json object. I can reuse the same writing routines. Does this make sense?
I am new to your library, maybe there is a workaround to get what I need with the current interface.