Skip to content

Conversation

@gbooker
Copy link

@gbooker gbooker commented Dec 13, 2021

I had a case where I needed to conditionally include members of a struct in json serialization based on certain criteria. Rather than create structs for each possible combination I wanted to indicate which fields should be present in the resulting json. Using std::optional is the obvious choice to indicate as to whether the field should be present in the json representation. Non-optional fields work as before.

Usage:

  struct OptionalFields
  {
    std::optional<int> count;
    std::optional<string> str;

    JSON5_MEMBERS(count, str);
  };

  struct OptionalArray
  {
    std::vector<OptionalFields> fields;

    JSON5_MEMBERS(fields);
  };

  OptionalArray array
  {
    {
      {1, {}},
      {2, ""},
      {{}, ""},
      {{}, {}},
      {5, "Golden Rings"},
    },
  };

  string json = json5::to_string(array);

results in:

{
  fields: [
    {
      count: 1
    },
    {
      count: 2,
      str: ""
    },
    {
      str: ""
    },
    {},
    {
      count: 5,
      str: "Golden Rings"
    }
  ]
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants