Parsing JSON using Qt 5 framework

Hello friends!

In one of my previous posts, we had seen how to send a HTTP request using Qt. The response we got then was a JSON string. JSON is a subset of the object literal notation of JavaScript. It is basically a lightweight data-interchange format making it easy for humans to read and write. A JSON is build on two structures namely,

  • A collection of name/value pairs. In various languages, this is realized as an object, record, struct, dictionary, hash table, keyed list or associative array.
  • An ordered list of values. In most languages, this is realized as an array, vector, list or sequence.

A sample valid JSON looks as follows:

{"success":"true","controls":[{"controlID":"1","type":"TEXTBOX"},{"controlID":"4","type":"CHECKBOX"}]}
  • An object is an un-ordered set of name/value pairs.
  • An object begins with { (left brace) and ends with } (right brace). Each name is followed by : (colon) and the name/value pairs are separated by , (comma).
  • On the other hand, an array is an ordered collection of values. An array begins with [ (left bracket) and ends with ] (right bracket). Values are separated by , (comma).

Through this post, we will learn to parse JSON using Qt 5.

Pre-requisites: Qt Creator, MinGW compiler (Windows - 64 bit)

Launch Qt Creator and create a new Qt console application project called TestJsonParsing. Choose the default Desktop kit.

Now, let’s add our JSON parser code in the main.cpp file as follows!

main.cpp

#include <QCoreApplication>
#include <QDebug>
#include <QApplication>
#include <QtWebKitWidgets/QWebFrame>
#include <QtWebKitWidgets/QWebPage>
#include <QtWebKitWidgets/QWebView>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QUrl>
#include <QUrlQuery>
#include <QWebSettings>
#include <QVariant>
#include <QJsonValue>
#include <QJsonDocument>
#include <QJsonObject>
#include <QVariantMap>
#include <QJsonArray>

void sendRequest();

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);
    sendRequest();
    return a.exec();
}

void sendRequest() {

    // create custom temporary event loop on stack
    QEventLoop eventLoop;

    // "quit()" the event-loop, when the network request "finished()"
    QNetworkAccessManager mgr;
    QObject::connect(&mgr, SIGNAL(finished(QNetworkReply*)), &eventLoop, SLOT(quit()));

    // the HTTP request
    QNetworkRequest req( QUrl( QString("http://time.jsontest.com/") ) );
    QNetworkReply *reply = mgr.get(req);
    eventLoop.exec(); // blocks stack until "finished()" has been called

    if (reply->error() == QNetworkReply::NoError) {

        QString strReply = (QString)reply->readAll();

        //parse json
        qDebug() << "Response:" << strReply;
        QJsonDocument jsonResponse = QJsonDocument::fromJson(strReply.toUtf8());

        QJsonObject jsonObj = jsonResponse.object();

        qDebug() << "Time:" << jsonObj["time"].toString();
        qDebug() << "Date:" << jsonObj["date"].toString();

        delete reply;
    }
    else {
        //failure
        qDebug() << "Failure" <<reply->errorString();
        delete reply;
    }
}

*.pro file

QT  += core
QT  -= gui
QT  += network
QT  += webkit webkitwidgets

TARGET = TestJsonParsing
CONFIG   += console
CONFIG   -= app_bundle

TEMPLATE = app

SOURCES += main.cpp

Save all changes. Build and run the application. If no errors are present then you should see the following output!

qt-json-parsing-output

That’s it then for this useful Qt tip. Hope it helps! :)

Reference: QJsonDocument, QJsonArray