I am reading the QJsonDocument documentation and I use QJsonDocument
with following line:
emit this->ueSignalNewDataArrivedPlaces(QJsonDocument::fromBinaryData(incomingData[0].toByteArray()));
and I do not understand, after this line, should I use QJsonDocument::array() or QJsonDocument::object(), i.e., in what situations does QJsonDocument
create array
and in what situations does create object
?
A JSON array is an ordered list, it is written as:
[ <item1>, <item2>, <item3> ]
while a JSON object is a named list, written as:
{
<name1>: <item1>,
<name2>: <item2>
}
In Qt, a QJsonArray
is equivalent to a QVariantList
(QList<QVariant>
) and a QJsonObject
is equivalent to QVariantMap
(QMap<QString, QVariant>
).
Which one you have to use depends on the file you are parsing. For instance, taking Wikipedia example:
{
"firstName": "John",
"lastName": "Smith",
"isAlive": true,
"age": 25,
"address": {
"streetAddress": "21 2nd Street",
"city": "New York",
"state": "NY",
"postalCode": "10021-3100"
},
"phoneNumbers": [
{
"type": "home",
"number": "212 555-1234"
},
{
"type": "office",
"number": "646 555-4567"
},
{
"type": "mobile",
"number": "123 456-7890"
}
],
"children": [],
"spouse": null
}
You would use a QJsonArray
to get the list of phoneNumbers
, each element of phoneNumbers
is a QJsonObject
whith 2 named values: type
and number
.
If in your code you need to manipulate a JSON element but you do not know its type you can use QJsonValue
, which is one of: QJsonObject
, QJsonArray
, bool
, double
or a QString