Using JSON in Modern C++

Serializing private class members to JSON

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

Abstract art representing computer programming

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.

Answers to questions are automatically generated and may not have been reviewed.

Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright © 2024 - All Rights Reserved