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 is going to 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 writePlayerInfo(const PlayerInfo &pinfo) const; };
All that is really required is to implement the writePlayerInfo
method. This method will use QJsonDocument::fromVariant()
to perform the serialization; thus, what we really have to do is convert our player data to a variant. Let's add a protected method to do that:
QVariant PlayerInfoJSON::toVariant(const PlayerInfo &pinfo) const { QVariantList players; foreach(const Player &p, pinfo.players) players << toVariant(p); return players; }
Since the structure is really a list of players, we can iterate the list of players, serialize...