JSON Save Game Example#

The JSON Save Game example demonstrates how to save and load a small game using QJsonDocument , QJsonObject and QJsonArray .

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 CBOR 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():

    Q_GADGET
# public
    ClassType = {
        Warrior, Mage, Archer

    Q_ENUM(ClassType)
    Character()
    Character(QString name, int level, ClassType classType)
    name = QString()
    def setName(name):
    level = int()
    def setLevel(level):
    classType = ClassType()
    def setClassType(classType):
    def read(json):
    def write(json):
    def print(0):
# private
    mName = QString()
    mLevel = int()
    mClassType = ClassType()

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

def read(self, json):

    if (json.contains("name") and json["name"].isString())
        mName = json["name"].toString()
    if (json.contains("level") and json["level"].isDouble())
        mLevel = json["level"].toInt()
    if (json.contains("classType") and json["classType"].isDouble())
        mClassType = ClassType(json["classType"].toInt())

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

def write(self, json):

    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 : operator[]() and insert() . Both will override any existing value at the given key.

Next up is the Level class:

class Level():

# public
    Level() = default
    Level(QString name)
    name = QString()
npcs = QList()
    def setNpcs(npcs):
    def read(json):
    def write(json):
    def print(0):
# private
    mName = QString()
mNpcs = QList()

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.

def read(self, json):

    if (json.contains("name") and json["name"].isString())
        mName = json["name"].toString()
    if (json.contains("npcs") and json["npcs"].isArray()) {
        npcArray = json["npcs"].toArray()
        mNpcs.clear()
        mNpcs.reserve(npcArray.size())
        for npcIndex in range(0, npcArray.size()):
            npcObject = npcArray[npcIndex].toObject()
            npc = Character()
            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 array.

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.

def write(self, json):

    json["name"] = mName
    npcArray = QJsonArray()
    for npc in mNpcs:
        npcObject = QJsonObject()
        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
    SaveFormat = {
        Json, Binary

    player = Character()
levels = QList()
    def newGame():
    loadGame = bool(SaveFormat saveFormat)
    saveGame = bool(SaveFormat saveFormat)
    def read(json):
    def write(json):
    def print(0):
# private
    mPlayer = Character()
mLevels = QList()

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().

def newGame(self):

    mPlayer = Character()
    mPlayer.setName(QStringLiteral("Hero"))
    mPlayer.setClassType(Character::Archer)
    mPlayer.setLevel(QRandomGenerator.global().bounded(15, 21))
    mLevels.clear()
    mLevels.reserve(2)
    village = Level(QStringLiteral("Village"))
villageNpcs = QList()
    villageNpcs.reserve(2)
    villageNpcs.append(Character(QStringLiteral("Barry the Blacksmith"),
                                 QRandomGenerator.global().bounded(8, 11),
                                 Character::Warrior))
    villageNpcs.append(Character(QStringLiteral("Terry the Trader"),
                                 QRandomGenerator.global().bounded(6, 8),
                                 Character::Warrior))
    village.setNpcs(villageNpcs)
    mLevels.append(village)
    dungeon = Level(QStringLiteral("Dungeon"))
dungeonNpcs = QList()
    dungeonNpcs.reserve(3)
    dungeonNpcs.append(Character(QStringLiteral("Eric the Evil"),
                                 QRandomGenerator.global().bounded(18, 26),
                                 Character::Mage))
    dungeonNpcs.append(Character(QStringLiteral("Eric's Left Minion"),
                                 QRandomGenerator.global().bounded(5, 7),
                                 Character::Warrior))
    dungeonNpcs.append(Character(QStringLiteral("Eric's Right Minion"),
                                 QRandomGenerator.global().bounded(4, 9),
                                 Character::Warrior))
    dungeon.setNpcs(dungeonNpcs)
    mLevels.append(dungeon)

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

def read(self, json):

    if (json.contains("player") and json["player"].isObject())
        mPlayer.read(json["player"].toObject())
    if (json.contains("levels") and json["levels"].isArray()) {
        levelArray = json["levels"].toArray()
        mLevels.clear()
        mLevels.reserve(levelArray.size())
        for levelIndex in range(0, levelArray.size()):
            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 level array so that calling loadGame() on the same Game object twice doesn’t result in old levels hanging around.

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

def write(self, json):

    playerObject = QJsonObject()
    mPlayer.write(playerObject)
    json["player"] = playerObject
    levelArray = QJsonArray()
    for level in mLevels:
        levelObject = QJsonObject()
        level.write(levelObject)
        levelArray.append(levelObject)

    json["levels"] = levelArray

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

def loadGame(self, Game::SaveFormat saveFormat):

    QFile loadFile(saveFormat == Json
        ? QStringLiteral("save.json")
    QStringLiteral.__init__(self, "save.dat"))
    if (not loadFile.open(QIODevice.ReadOnly)) {
        qWarning("Couldn't open save file.")
        return False

    saveData = loadFile.readAll()
    QJsonDocument loadDoc(saveFormat == Json
        ? QJsonDocument.fromJson(saveData)
    QJsonDocument.__init__(self, QCborValue.fromCbor(saveData).toMap().toJsonObject()))
    read(loadDoc.object())
    QTextStream(stdout) << "Loaded save for "
                        << loadDoc["player"]["name"].toString()
                        << " using "
                        << (saveFormat != Json if "CBOR" else "JSON") << "...\n"
    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 CBOR. We print a warning and return false if the file couldn’t be opened.

Since fromJson() and fromCbor() 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.

def saveGame(self, Game::SaveFormat saveFormat):

    QFile saveFile(saveFormat == Json
        ? QStringLiteral("save.json")
    QStringLiteral.__init__(self, "save.dat"))
    if (not saveFile.open(QIODevice.WriteOnly)) {
        qWarning("Couldn't open save file.")
        return False

    gameObject = QJsonObject()
    write(gameObject)
    saveFile.write(saveFormat == Json
        ? QJsonDocument(gameObject).toJson()
    QCborValue.fromJsonValue.__init__(self, gameObject).toCbor())
    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 toJson() or to QJsonDocument::toBinaryData() to save the game, depending on which format was specified.

We are now ready to enter main():

if __name__ == "__main__":

    app = QCoreApplication(argc, argv)
    args = QCoreApplication.arguments()
    newGame = True()
    if (args.length() > 1)
        newGame = (args[1].toLower() != QStringLiteral("load"))
    json = True()
    if (args.length() > 2)
        json = (args[2].toLower() != QStringLiteral("binary"))
    game = Game()
    if (newGame)
        game.newGame()
    elif not game.loadGame(json if Game.Json else Game.Binary):
            return 1
    # 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. On application start-up we parse the command-line arguments to decide how to start the game. For the first argument the options “new” (default) and “load” are available. When “new” is specified a new game will be generated, and when “load” is specified a previously saved game will be loaded in. For the second argument “json” (default) and “binary” are available as options. This argument will decide which file is saved to and/or loaded from. We then move ahead 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.

QTextStream(stdout) << "Game ended in the following state:\n"
game.print()
if (not game.saveGame(json if Game.Json else Game.Binary))
    return 1
return 0

When the player has finished, we save their game. For demonstration purposes, we can serialize to either JSON or CBOR. You can examine the contents of the files in the same directory as the executable (or re-run the example, making sure to also specify the “load” option), although the binary save file will contain some garbage characters (which is normal).

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.

See also

JSON Support in Qt Data Storage

Example project @ code.qt.io