如何使用QJsonArray在Qt5(C ++)中解析JSON文件(Array)

时间:2017-06-26 19:07:06

标签: c++ json qt qt5

我正在考虑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();

1 个答案:

答案 0 :(得分:1)

由于数据没有JSON格式(格式不正确,请参阅RFC 7159),但如果它是部分内容,我们必须做的是将它分开,因为我们使用{{1我们验证数据是否具有适当的格式,然后代码与您的代码类似。

<强>代码:

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();
}