简体   繁体   中英

Parsing JSON starting with bracket `[` with Qt5

According to this , A JSON starting with bracket is valid, so i have encoded a list of item, in a test.json file:

[{"name": "a"},{"name": "b"}]

Heavily inspirated by this answer , i push this code in main.cpp :

#include <QApplication>
#include <QFile>
#include <QByteArray>
#include <QJsonObject>
#include <QJsonDocument>
#include <QVariant>
#include <QDebug>
#include <iostream>


int main(int argc, char *argv[]) {
      // Reading the JSON, parse it, get data as QJsonObject
      QString val;
      QFile file;
      file.setFileName("test.json");
      file.open(QIODevice::ReadOnly | QIODevice::Text);
      val = file.readAll();
      file.close();
      QJsonDocument d = QJsonDocument::fromJson(val.toUtf8());
      QJsonObject sett2 = d.object();

      // Printings
      qWarning() << "File content: " << val;
      qWarning() << "sett2: " << sett2 << " (empty: " << sett2.empty() << ')';

      // try to access the data directly
      QJsonValue value = sett2.value(QString("name"));
      qWarning() << "name value: " << value;
      QJsonObject item = value.toObject();
      qWarning() << "QJsonObject of accessed value: " << item;
}

Here is the output:

File content: "[{\"name\": \"a\"},{\"name\": \"b\"}]\n"
sett2:  QJsonObject()  (empty:  true )
name value: QJsonValue(undefined)
QJsonObject of accessed value:  QJsonObject()

We see that the file is properly readed. However, no data seems to be accessed : sett2 is empty, as if holding no data.

After searching on the QJsonObject documentation, i can't found any routine that can give access to the data in the file, in this case: the only one that seems to allow an access to fields is the value() , method, but it needs a parameter. Call it with 0 , 1 , NULL "name" , "a" , "b" and "knock knock" lead to compilation error or empty data. Other methods, like keys() , returns also empty data.

How access data of objects ? (here, name: "a" and name: "b" )

QJsonDocument::array()很简单-您必须调用QJsonDocument::array()而不是object

QJsonArray sett2 = d.array();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM