boostorg / describe

A C++14 reflection library
https://boost.org/libs/describe
69 stars 24 forks source link

Describe and json serialization with containers #25

Closed vricosti closed 2 years ago

vricosti commented 2 years ago

Hello,

Let's say I have the following struct:

struct Item
   {
      std::string id;
      std::string label;
      std::string iconFile;
   };
   BOOST_DESCRIBE_STRUCT(Item, (), (id, label, iconFile))

When I serialize in json the following code:

Item item = { "anId", "aLabel", "anIcon"};
 std::stringstream ss;
 ss << boost::json::value_from(item);

I get the following json:

{"id":"anId","label":"aLabel","iconFile":"anIcon"}

Would it be possible to have directly:

{ "item": {"id":"anId","label":"aLabel","iconFile":"anIcon"} }

Without having to write:

boost::json::object jObj;
jObj["item"] = boost::json::value_from(item);
auto msg = boost::json::serialize(jObj);

Thanks

pdimov commented 2 years ago

The JSON you want corresponds to a struct having Item as the only member, something like

struct X
{
    Item item;
};
BOOST_DESCRIBE_STRUCT(X, (), (item))