Reputation: 41
I'm using QJsonDocument::toJson to convert a QJsonObject into a QByteArray, and somewhere else in the program, I read that QByteArray and convert it to a QJsonObject using QJsonDocument::fromJson. It doesn't work and I don't know why. QJsonParseError doesn't show anything.
How can I successfully convert to and from QByteArray <--> QJsonObject?
If I run:
QJsonDocument doc, doc2;
QJsonParseError jsonerror;
QJsonObject original, copy;
original.insert("foo", 1);
original.insert("bar",2);
doc.setObject(original);
doc2.fromJson(doc.toJson(), &jsonerror);
copy = doc2.object();
qDebug() << doc.toJson();
qDebug() << jsonerror.errorString();
qDebug() << "Null: " << doc2.isNull() << " Object: " << doc2.isObject() << " Array: " << doc2.isArray() << " Empty: " << doc2.isEmpty();
qDebug() << copy.size();
I get the following output:
"{\n "bar": 2,\n "foo": 1\n}\n"
"no error occurred"
Null: true Object: false Array: false Empty: true
0
I expected the object copy
to contain the key-value pairs from original
. It seems like fromJson is not managing to read the result of toJson.
I also tried using the format identifier in toJson to force it to be compact doc2.fromJson(doc.toJson(QJsonDocument::Compact), &jsonerror);
and while the output is different, the resulting object is still empty
"{"bar":2,"foo":1}"
"no error occurred"
Null: true Object: false Array: false Empty: true
0
Upvotes: 1
Views: 293
Reputation: 41
The method fromJson is a static member function, so calling doc2.fromJson(...)
does not change anything inside doc2, instead it constructs a new QJsonDocument and as it has nowhere to go (it is not assigned to anything) it is lost.
This is the example above corrected:
QJsonDocument doc;
QJsonParseError jsonerror;
QJsonObject original, copy;
original.insert("foo", 1);
original.insert("bar",2);
doc.setObject(original);
QJsonDocument doc2 = QJsonDocument::fromJson(doc.toJson(), &jsonerror);
copy = doc2.object();
qDebug() << doc.toJson();
qDebug() << jsonerror.errorString();
qDebug() << "Null: " << doc2.isNull() << " Object: " << doc2.isObject() << " Array: " << doc2.isArray() << " Empty: " << doc2.isEmpty();
qDebug() << copy.size();
Which generates the output:
"{\n "bar": 2,\n "foo": 1\n}\n"
"no error occurred"
Null: false Object: true Array: false Empty: false
2
Upvotes: 3