O'Reilly logo

Game Programming Using Qt by Lorenz Haas, Witold Wysota

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Time for action – implementing a JSON parser

Let's extend the PlayerInfoJSON class and equip it with a reverse conversion:

PlayerInfo PlayerInfoJSON::readPlayerInfo(const QByteArray &ba) const {
  QJsonDocument doc = QJsonDocument::fromJson(ba);
  if(doc.isEmpty() || !doc.isArray()) return PlayerInfo();
  return readPlayerInfo(doc.array());
}

First, we read the document and check whether it is valid and holds the expected array. Upon failure, an empty structure is returned; otherwise, readPlayerInfo is called and is given QJsonArray to work with:

PlayerInfo PlayerInfoJSON::readPlayerInfo(const QJsonArray &array) const {
  PlayerInfo pinfo;
  foreach(QJsonValue value, array)
    pinfo.players << readPlayer(value.toObject());
  return pinfo;
}

Since the array is iterable, ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required