Qt 5.6 | Qt Core | JSON Save Game Example

Qt 5.6.2 Reference Documentation

# JSON Save Game Example

Many games provide save functionality, so that the player's progress through the game can be saved and loaded at a later time. The process of saving a game generally involves serializing each game object's member variables to a file. Many formats can be used for this purpose, one of which is JSON. With QJsonDocument, you also have the ability to serialize a document in a binary format, which is great if you don't want the save file to be readable, or if you need to keep the file size down.

In this example, we'll demonstrate how to save and load a simple game to and from JSON and binary formats.

## The Character Class

The Character class represents a non-player character (NPC) in our game, and stores the player's name, level, and class type.

It provides read() and write() functions to serialise its member variables.

      class Character
      {
      public:
          enum ClassType {
              Warrior, Mage, Archer
          };

          Character();
          Character(const QString &name, int level, ClassType classType);

          QString name() const;
          void setName(const QString &name);

          int level() const;
          void setLevel(int level);

          ClassType classType() const;
          void setClassType(ClassType classType);

          void read(const QJsonObject &json);
          void write(QJsonObject &json) const;
      private:
          QString mName;
          int mLevel;
          ClassType mClassType;
      };

Of particular interest to us are the read and write function implementations:

      void Character::read(const QJsonObject &json)
      {
          mName = json["name"].toString();
          mLevel = json["level"].toDouble();
          mClassType = ClassType(qRound(json["classType"].toDouble()));
      }

In the read() function, we assign Character's members values from the QJsonObject argument. You can use either QJsonObject::operator[]() or QJsonObject::value() to access values within the JSON object; both are const functions and return QJsonValue::Undefined if the key is invalid. We could check if the keys are valid before attempting to read them with QJsonObject::contains(), but we assume that they are.

      void Character::write(QJsonObject &json) const
      {
          json["name"] = mName;
          json["level"] = mLevel;
          json["classType"] = mClassType;
      }

In the write() function, we do the reverse of the read() function; assign values from the Character object to the JSON object. As with accessing values, there are two ways to set values on a QJsonObject: QJsonObject::operator[]() and QJsonObject::insert(). Both will override any existing value at the given key.

Next up is the Level class:

      class Level
      {
      public:
          Level();

          const QList<Character> &npcs() const;
          void setNpcs(const QList<Character> &npcs);

          void read(const QJsonObject &json);
          void write(QJsonObject &json) const;
      private:
          QList<Character> mNpcs;
      };

We want to have several levels in our game, each with several NPCs, so we keep a QList of Character objects. We also provide the familiar read() and write() functions.

      void Level::read(const QJsonObject &json)
      {
          mNpcs.clear();
          QJsonArray npcArray = json["npcs"].toArray();
          for (int npcIndex = 0; npcIndex < npcArray.size(); ++npcIndex) {
              QJsonObject npcObject = npcArray[npcIndex].toObject();
              Character npc;
              npc.read(npcObject);
              mNpcs.append(npc);
          }
      }

Containers can be written and read to and from JSON using QJsonArray. In our case, we construct a QJsonArray from the value associated with the key `"npcs"`. Then, for each QJsonValue element in the array, we call toObject() to get the Character's JSON object. The Character object can then read their JSON and be appended to our NPC list.

Note: Associate containers can be written by storing the key in each value object (if it's not already). With this approach, the container is stored as a regular array of objects, but the index of each element is used as the key to construct the container when reading it back in.

      void Level::write(QJsonObject &json) const
      {
          QJsonArray npcArray;
          foreach (const Character npc, mNpcs) {
              QJsonObject npcObject;
              npc.write(npcObject);
              npcArray.append(npcObject);
          }
          json["npcs"] = npcArray;
      }

Again, the write() function is similar to the read() function, except reversed.

Having established the Character and Level classes, we can move on to the Game class:

      class Game
      {
      public:
          Game();

          enum SaveFormat {
              Json, Binary
          };

          const Character &player() const;
          const QList<Level> &levels() const;

          void newGame();
          bool loadGame(SaveFormat saveFormat);
          bool saveGame(SaveFormat saveFormat) const;

          void read(const QJsonObject &json);
          void write(QJsonObject &json) const;
      private:
          Character mPlayer;
          QList<Level> mLevels;
      };

First of all, we define the `SaveFormat` enum. This will allow us to specify the format in which the game should be saved: `Json` or `Binary`.

Next, we provide accessors for the player and levels. We then expose three functions: newGame(), saveGame() and loadGame().

The read() and write() functions are used by saveGame() and loadGame().

      void Game::newGame() {
          mPlayer = Character();
          mPlayer.setName(QStringLiteral("Hero"));
          mPlayer.setClassType(Character::Archer);
          mPlayer.setLevel(15);

          mLevels.clear();

          Level village;
          QList<Character> villageNpcs;
          villageNpcs.append(Character(QStringLiteral("Barry the Blacksmith"), 10, Character::Warrior));
          villageNpcs.append(Character(QStringLiteral("Terry the Trader"), 10, Character::Warrior));
          village.setNpcs(villageNpcs);
          mLevels.append(village);

          Level dungeon;
          QList<Character> dungeonNpcs;
          dungeonNpcs.append(Character(QStringLiteral("Eric the Evil"), 20, Character::Mage));
          dungeonNpcs.append(Character(QStringLiteral("Eric's Sidekick #1"), 5, Character::Warrior));
          dungeonNpcs.append(Character(QStringLiteral("Eric's Sidekick #2"), 5, Character::Warrior));
          dungeon.setNpcs(dungeonNpcs);
          mLevels.append(dungeon);
      }

To setup a new game, we create the player and populate the levels and their NPCs.

      void Game::read(const QJsonObject &json)
      {
          mPlayer.read(json["player"].toObject());

          mLevels.clear();
          QJsonArray levelArray = json["levels"].toArray();
          for (int levelIndex = 0; levelIndex < levelArray.size(); ++levelIndex) {
              QJsonObject levelObject = levelArray[levelIndex].toObject();
              Level level;
              level.read(levelObject);
              mLevels.append(level);
          }
      }

The first thing we do in the read() function is tell the player to read itself. We then clear the levels list so that calling loadGame() on the same Game object twice doesn't result in old levels hanging around.

We then populate the level list by reading each Level from a QJsonArray.

      void Game::write(QJsonObject &json) const
      {
          QJsonObject playerObject;
          mPlayer.write(playerObject);
          json["player"] = playerObject;

          QJsonArray levelArray;
          foreach (const Level level, mLevels) {
              QJsonObject levelObject;
              level.write(levelObject);
              levelArray.append(levelObject);
          }
          json["levels"] = levelArray;
      }

We write the game to JSON similarly to how we write Level.

      bool Game::loadGame(Game::SaveFormat saveFormat)
      {
          QFile loadFile(saveFormat == Json
              ? QStringLiteral("save.json")
              : QStringLiteral("save.dat"));

          if (!loadFile.open(QIODevice::ReadOnly)) {
              qWarning("Couldn't open save file.");
              return false;
          }

          QByteArray saveData = loadFile.readAll();

          QJsonDocument loadDoc(saveFormat == Json
              ? QJsonDocument::fromJson(saveData)
              : QJsonDocument::fromBinaryData(saveData));

          read(loadDoc.object());

          return true;
      }

When loading a saved game in loadGame(), the first thing we do is open the save file based on which format it was saved to; `"save.json"` for JSON, and `"save.dat"` for binary. We print a warning and return `false` if the file couldn't be opened.

Since QJsonDocument's fromJson() and fromBinaryData() functions both take a QByteArray, we can read the entire contents of the save file into one, regardless of the save format.

After constructing the QJsonDocument, we instruct the Game object to read itself and then return `true` to indicate success.

      bool Game::saveGame(Game::SaveFormat saveFormat) const
      {
          QFile saveFile(saveFormat == Json
              ? QStringLiteral("save.json")
              : QStringLiteral("save.dat"));

          if (!saveFile.open(QIODevice::WriteOnly)) {
              qWarning("Couldn't open save file.");
              return false;
          }

          QJsonObject gameObject;
          write(gameObject);
          QJsonDocument saveDoc(gameObject);
          saveFile.write(saveFormat == Json
              ? saveDoc.toJson()
              : saveDoc.toBinaryData());

          return true;
      }

Not surprisingly, saveGame() looks very much like loadGame(). We determine the file extension based on the format, print a warning and return `false` if the opening of the file fails. We then write the Game object to a QJsonDocument, and call either QJsonDocument::toJson() or to QJsonDocument::toBinaryData() to save the game, depending on which format was specified.

We are now ready to enter main():

      int main(int argc, char *argv[])
      {
          QCoreApplication app(argc, argv);

          Game game;
          game.newGame();
          // Game is played; changes are made...

Since we're only interested in demonstrating serialization of a game with JSON, our game is not actually playable. Therefore, we only need QCoreApplication and have no event loop. We create our game and assume that the player had a great time and made lots of progress, altering the internal state of our Character, Level and Game objects.

          if (!game.saveGame(Game::Json))
              return 1;

          if (!game.saveGame(Game::Binary))
              return 1;

          Game fromJsonGame;
          if (!fromJsonGame.loadGame(Game::Json))
              return 1;

          Game fromBinaryGame;
          if (!fromBinaryGame.loadGame(Game::Binary))
              return 1;

          return 0;
      }

When the player has finished, we save their game. For demonstration purposes, we serialize to both JSON and binary. You can examine the contents of the files in the same directory as the executable, although the binary save file will contain some garbage characters (which is normal).

To show that the saved files can be loaded again, we call loadGame() for each format, returning `1` on failure. Assuming everything went well, we return `0` to indicate success.

That concludes our example. As you can see, serialization with Qt's JSON classes is very simple and convenient. The advantages of using QJsonDocument and friends over QDataStream, for example, is that you not only get human-readable JSON files, but you also have the option to use a binary format if it's required, without rewriting any code.

Files:

- json/savegame/character.cpp
- json/savegame/character.h
- json/savegame/game.cpp
- json/savegame/game.h
- json/savegame/level.cpp
- json/savegame/level.h
- json/savegame/main.cpp
- json/savegame/savegame.pro

See also JSON Support in Qt and Data Storage.