Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for optionals #2

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open

Add support for optionals #2

wants to merge 3 commits into from

Conversation

gbooker
Copy link
Contributor

@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.

1 participant