0

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

RGPaul
  • 401
  • 1
  • 4
  • 11

1 Answers1

0

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.

RGPaul
  • 401
  • 1
  • 4
  • 11
  • It's not an issue with C++11; it's the [documented behaviour](http://doc.qt.io/qt-5/qjsonarray.html#QJsonArray-2). When you use the initializer-list, It converts your 1st array into a single QJsonValue. So, *results* becomes an array-of-an-array. The behaviour you saw with Qt 5.3 was buggy. – JKSH Jan 22 '15 at 23:52