如何使用QJSONARRAY在QT5(C )中解析JSON文件(数组)

How to parsing JSON file(Array) in Qt5 (C++), using QJsonArray

本文关键字:JSON 数组 文件 何使用 QJSONARRAY QT5      更新时间:2023-10-16

我正在tring qt5。我尝试从JSON文件读取值。JSON文件就像上面的文件:

test.json

[{"w":188,"h":334,"th":0.350000,"l":232,"r":420,"t":133,"b":467,"p":0.713963,"n":"person"}]
[{"w":127,"h":141,"th":0.350000,"l":1152,"r":1279,"t":162,"b":303,"p":0.408129,"n":"person"},{"w":179,"h":339,"th":0.350000,"l":230,"r":409,"t":131,"b":470,"p":0.698172,"n":"person"}]

我尝试的是代码。如何读取这样的JSON文件结构?

QString val;
QFile file;
file.setFileName("test.json");
file.open(QIODevice::ReadOnly | QIODevice::Text);
//file is readall
val = file.readAll();
file.close();
qWarning() << val; //print consol
QJsonDocument jsonDocument = QJsonDocument::fromJson(val.toUtf8());
//get data array !!!
QJsonObject jsonObject = jsonDocument.object();
QJsonArray jsonArray = jsonObject["w"].toArray();
qWarning() << jsonArray[0].toString();

由于数据没有JSON格式(它是不形式的,请参见RFC 7159(,但是如果它是部分的,我们必须做的就是将其分开,因为我们使用QRegularExpresion,并验证数据是否具有适当的格式,然后代码类似于您的代码。

代码:

#include <QCoreApplication>
#include <QFile>
#include <QDebug>
#include <QRegularExpression>
#include <QJsonDocument>
#include <QJsonArray>
#include <QJsonObject>
int main(int argc, char *argv[]){
    QCoreApplication a(argc, argv);
    QFile file("test.json");
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)){
        qWarning() << "Could not open file!";
        return 0;
    }
    const auto& data = QString(file.readAll());
    file.close();
    QRegularExpression regex("\[|\]");
    const auto& jsons = data.split(regex);
    for(const auto& json : jsons)
        if(!json.trimmed().isEmpty()){
            const auto& formattedJson = QString("[%1]").arg(json);
            const auto& doc = QJsonDocument::fromJson(formattedJson.toUtf8());
            if(doc.isArray())
                for(const auto& item : doc.array()){
                    const auto& obj = item.toObject();
                    const auto& keys = obj.keys();
                    for(const auto& key : keys){
                        if(key == "n")
                            qDebug() << key << obj[key].toString();
                        else
                            qDebug() << key << obj[key].toInt();
                    }
                }
        }
    return a.exec();
}

输出:

"b" 467
"h" 334
"l" 232
"n" "person"
"p" 0
"r" 420
"t" 133
"th" 0
"w" 188
"b" 303
"h" 141
"l" 1152
"n" "person"
"p" 0
"r" 1279
"t" 162
"th" 0
"w" 127
"b" 470
"h" 339
"l" 230
"n" "person"
"p" 0
"r" 409
"t" 131
"th" 0
"w" 179