[Solved] QJsonDocument parsing issue Qt 5.3 vs. Qt 5.4 on OSX using C++11
-
Hi there,
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 -
Hi and welcome to devnet,
Can't really comment on this, the only thing I can say is that it works fine when not using C++11
-
Sill, it's a bit strange that it worked with Qt 5.3 and not 5.4
Did you change anything else in between ? (e.g. compiler)
-
Then I'd recommend checking the "bug report system":http://bugreports.qt.io to see if it's something known. If not please consider opening a new report providing a minimal compilable example to reproduce the behavior
-
The Qt 5.4 behaviour is the correct, "documented":http://doc.qt.io/qt-5/qjsonarray.html#QJsonArray-2 one.
rootObj.value("results").toArray() returns a QJsonArray containing 4 elements. However, by using the initializer-list, this array is first converted into a single QJsonValue. Then, this single QJsonValue is stored in the outer array. That's why the outer array reports having 1 element.
Do this and you will see that you have a 2D array (more precisely, it's an array-within-an-array):
@
QJsonArray results{ rootObj.value("results").toArray() };
qDebug() << results;
@Do this and you will see that you have a 1D array:
@
QJsonArray results = rootObj.value("results").toArray();
qDebug() << results;
@ -
You're welcome :)
-
Okay… Just saw that my offline doc was from the wrong Qt version :D
Thanks for the explanation JKSH