Time for action – The player data JSON serializer

Our next exercise is to create a serializer of the same PlayerInfo structure as we used for the XML exercise, but this time the destination data format will be JSON.

Start by creating a PlayerInfoJson class and give it an interface similar to the one shown in the following code:

class PlayerInfoJson {
public:
    PlayerInfoJson() {}
    QByteArray playerInfoToJson(const PlayerInfo &pinfo);
}; 

All that is really required is to implement the playerInfoToJson method. Generally, we need to convert our PlayerInfo data to a QJsonArray and then use QJsonDocument to encode it as JSON:

QByteArray PlayerInfoJson::playerInfoToJson(const PlayerInfo &pinfo) { QJsonDocument doc(toJson(pinfo)); return doc.toJson(); ...

Get Game Programming using Qt 5 Beginner's Guide - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.