Skip to content

Dynamic JSON objects with static serialization/deserialization? #1131

Answered by stephenberry
ethindp asked this question in Q&A
Discussion options

You must be logged in to vote

Dynamic types like this can be handled through maps and variants. Here is a somewhat simplified example without all the fields, but should give you an idea of the approach:

struct string_t
{
  bool enabled{};
  bool readonly{};
  std::string value{};
};

struct int_t
{
  bool enabled{};
  int max{};
  int min{};
  bool readonly{};
  std::vector<int> values{};
  int value{};
};

using properties_t = std::variant<string_t, int_t>;

template <>
struct glz::meta<properties_t>
{
   static constexpr std::string_view tag = "type";
   static constexpr auto ids = std::array{"string", "int"};
};

struct children_t
{
  std::unordered_map<std::string, properties_t> devices{};
};

struct data_t
{
  st…

Replies: 4 comments 3 replies

Comment options

You must be logged in to vote
0 replies
Answer selected by ethindp
Comment options

You must be logged in to vote
1 reply
@stephenberry
Comment options

Comment options

You must be logged in to vote
1 reply
@stephenberry
Comment options

Comment options

You must be logged in to vote
1 reply
@stephenberry
Comment options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants