niXman / yas

Yet Another Serialization
731 stars 95 forks source link

How to dynamically create a YAS_OBJECT_NVP item object? #119

Closed imichael66 closed 2 years ago

imichael66 commented 2 years ago

Hi, Could you help on how to dynamically create a YAS_OBJECT_NVP item and add it to an already existing object?

use case:

auto Person=YAS_OBJECT_NVP("OBJ",("name","a_name")); auto surname=YAS_OBJECT("surname","a_surname");//or surname=make_object(... Person+=surname;//wish this had been feasible!?

Best regards and thanks for this great library!

niXman commented 2 years ago

hi,

you can not. this was the main purpose of the JSON implementation in YAS, namely to use statically generated C++ types and this is the reason for such a high speed of serialization and deserialization in YAS. most JSON libraries for C++ "construct" JSON types dynamically, which is why they are incredibly slow...

you can use this trick:

if ( has_surname ) {
   auto o = YAS_OBJECT_NVP("OBJ",("name","a_name"), ("surname", surname_var));
   save(..., o);
} else {
   auto o = YAS_OBJECT_NVP("OBJ",("name","a_name"));
   save(..., o);
}
niXman commented 2 years ago

also you can use YAS objects in YAS objects:

auto s = YAS_OBJECT_NVP("OBJ",("surname",surname_var));
auto o = YAS_OBJECT_NVP("OBJ",("name","a_name"), ("surname", s));
save(..., o);
niXman commented 2 years ago

please close the issue if you have no more questions.

imichael66 commented 2 years ago

Thanks for you reply. Closing issue.