Qt parse a json response

c++, json, parsing, qt

Solution

I would encourage you to use Qt 5 or backport the json classes to Qt 4. Your software will be more future proof then when you intend to port it to Qt 5 since you will need to rewrite the json parsing then available in QtCore.

I would write something like the code below, but please double check it before using it in production as I may have missed an error checking while writing it. Regardless of error checking, the output is what you wanted to get.

main.cpp

#include <QFile>
#include <QByteArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QDebug>

int main()
{
    QFile file("main.json");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "Could not open the file" << file.fileName() << "for reading:" << file.errorString();
        return 1;
    }

    QByteArray jsonData = file.readAll();
    if (file.error() != QFile::NoError) {
        qDebug() << QString("Failed to read from file %1, error: %2").arg(file.fileName()).arg(file.errorString());
        return 2;
    }

    if (jsonData.isEmpty()) {
        qDebug() << "No data was currently available for reading from file" << file.fileName();
        return 3;
    }

    QJsonDocument document = QJsonDocument::fromJson(jsonData);
    if (!document.isObject()) {
        qDebug() << "Document is not an object";
        return 4;
    }
    QJsonObject object = document.object();
    QJsonValue jsonValue = object.value("id");
    if (jsonValue.isUndefined()) {
        qDebug() << "Key id does not exist";
        return 5;
    }
    if (!jsonValue.isString()) {
        qDebug() << "Value not string";
        return 6;
    }

    qDebug() << jsonValue.toString();
    return 0;
}

main.pro

TEMPLATE = app
TARGET = main
QT = core
SOURCES += main.cpp

Build and Run

qmake && make && ./main

Output

"blabla2"

Problem

I need to parse a json response that looks like this and to get the id value, i.e. blabla2: ``` { "kind": "blabla", "id": "blabla2", "longUrl": "blabla3" } ``` How do I do that? I tried to use Qjson, but when I try to buid it to get the `.dll`, I get an error: xlocale.h is missing. Are there other alternatives? Thanks.

Original source