Search code examples
c++macosc++11qt5qjson

QJsonDocument parsing broken since Qt 5.4 on OSX?


I have problems parsing json since I upgraded to Qt 5.4.

Here is an example:

#include <QCoreApplication>

#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>

#include <QDebug>

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    char jsString[] {
        "{\"results\":[{\"id\":1,\"title\":\"Test1\"},{\"id\":2,\"title\":\""
        "Test2\"},{\"id\":3,\"title\":\"Test3\"},{\"id\":4,\"title\":\"Test4\"}]}"
    };

    QJsonParseError *error { nullptr };
    // parse bytes to json
    QJsonDocument doc { QJsonDocument::fromJson(jsString, error) };

    if (error) {
        qDebug() << "error parsing json:" << error->errorString();
    } else {

        QJsonObject rootObj { doc.object() };
        QJsonArray results { rootObj.value("results").toArray() };

        qDebug() << "results.count:" << results.count();

        for (QJsonValue v : results) {
            qDebug() << "v:" << v.toObject().value("title").toString();
        }
    }
    return a.exec();
}

If I run this using Qt 5.3 all is fine. The output is:

results.count: 4
v: "Test1"
v: "Test2"
v: "Test3"
v: "Test4"

If I run this using Qt 5.4 I get this:

results.count: 1
v: ""

I run this on Mac OS X Yosemite 64-Bit with the clang compiler.

Has anyone an idea whats wrong?

Cheers, Manromen


Solution

  • So it seems to be an issue with C++11.

    As mentioned by JKSH, Qt 5.4 added an initializer list to the constructor.

    I replaced:

    QJsonArray results { rootObj.value("results").toArray() };
    

    with:

    QJsonArray results = rootObj.value("results").toArray();
    

    Now it's working.