Parse jsonarray?

て烟熏妆下的殇ゞ 提交于 2019-12-03 07:28:28

问题


I've got an JSON like the following:

{
    "agentsArray": [{
        "ID": 570,
        "picture": "03803.png",
        "name": "Bob"
    }, {
        "ID": 571,
        "picture": "02103.png",
        "name": "Tina"
    }]
}

Now I'm trying to loop through each array element. Using the qt-json library https://github.com/da4c30ff/qt-json

Tried:

            foreach(QVariantMap plugin, result["agentsArray"].toList()) {
                qDebug() << "  -" << plugin["ID"].toString();
            }

But cannot get it to work, any ideas what I'm doing wrong?


回答1:


I would recommend using the QJson* classes from QtCore in Qt 5. They are very efficient due to the machine readable binary storage optimized for reading and writing, and it is also very convenient to use them due to the nice API they have.

This code base works for me just fine, but please note that I neglected all the error checking for now which is not a good advice for production code. This is just a prototype code, respectively.

main.json

{
    "agentsArray": [{
        "ID": 570,
        "picture": "03803.png",
        "name": "Bob"
    }, {
        "ID": 571,
        "picture": "02103.png",
        "name": "Tina"
    }]
}

main.cpp

#include <QFile>
#include <QByteArray>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QDebug>

int main()
{
    QFile file("main.json");
    file.open(QIODevice::ReadOnly | QIODevice::Text);
    QByteArray jsonData = file.readAll();
    file.close();

    QJsonDocument document = QJsonDocument::fromJson(jsonData);
    QJsonObject object = document.object();

    QJsonValue value = object.value("agentsArray");
    QJsonArray array = value.toArray();
    foreach (const QJsonValue & v, array)
        qDebug() << v.toObject().value("ID").toInt();

    return 0;
}

main.pro

TEMPLATE = app
TARGET = main
QT = core
SOURCES += main.cpp

Build and Run

qmake && make && ./main

Output

570 
571 


来源:https://stackoverflow.com/questions/23174393/parse-jsonarray

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!