Serializing private class members to JSON

How can I serialize private members of a class to JSON?

By default, the NLOHMANN_DEFINE_TYPE_NON_INTRUSIVE macro that's used to make a type serializable with the nlohmann::json library only works with public members.

To serialize private members, you have a couple of options:

Option 1: Make the private members public (not recommended, as it breaks encapsulation).

Option 2: Use the NLOHMANN_DEFINE_TYPE_INTRUSIVE macro instead and put it in the public section of your class:

class Character {
  std::string name;
  int level;

 public:
  NLOHMANN_DEFINE_TYPE_INTRUSIVE(
    Character, name, level)

  const std::string& getName() const {
    return name;
  }

  int getLevel() const { return level; }
};

Now name and level will be serialized even though they're private.

Option 3: Define your own to_json and from_json functions for the type:

class Character {
  std::string name;
  int level;

 public:
  const std::string& getName() const {
    return name; }
  int getLevel() const { return level; }

  friend void to_json(json& j,
    const Character& c) {
    j = json{
      {"name", c.name},
      {"level", c.level}
    };
  }

  friend void from_json(const json& j,
    Character& c) {
    j.at("name").get_to(c.name);
    j.at("level").get_to(c.level);
  }
};

By making the to_json and from_json functions friends of the Character class, they can access its private members.

Options 2 and 3 are the recommended ways to serialize private members, as they don't require changing your class's access controls. Which one you choose depends on whether you prefer the convenience of the macro or the flexibility of writing the functions yourself.

Using JSON in Modern C++

A practical guide to working with the JSON data format in C++ using the popular nlohmann::json library.

Questions & Answers

Answers are generated by AI models and may not have been reviewed. Be mindful when running any code on your device.

Creating a JSON object from a file
How can I create a JSON object by reading the contents of a JSON file?
Checking if a key exists in JSON
What is the best way to check if a specific key exists in a JSON object?
Pretty-printing JSON
How can I print out JSON in a nicely formatted way?
Using custom types as JSON keys
Can I use a custom type as a key in a JSON object?
Adding comments to JSON
Can I add comments to a JSON file to document what certain parts mean?
Or Ask your Own Question
Get an immediate answer to your specific question using our AI assistant