QT读取JSON文件并存储和检索值

QT Reading a JSON file and storing and retriving values

本文关键字:检索 存储 读取 JSON 文件 QT      更新时间:2023-10-16

我正在尝试读取如下QT中所示的json文件。有人能建议一种从json对象中获取值并将其存储在单独的容器或数组中的方法吗?比如test_cell2.CELLS[0],或者某种方法,这样也可以处理嵌套,而且我可以在解析文件后轻松访问它们

"test_cells2" : {
        "CELLS" : {
            "cell_0" : {
                "prettyName" : "cell_1",
                "CELLS" : {
                    "cell_1" : {
                        "prettyName" : "cell_1",
                        "type" : "default",
                    },
                },
            },
            "cell_1" : {
                "prettyName" : "cell_1",
                "type" : "default",
            },
            "cell_2" : {
                "type" : "text cell ko",
            },
            "cell_3" : {
                "prettyName" : "cell_3",
                "type" : "default",
            },
            "cell_4" : {
                "data" : {
                    "settings" : {
                        "EXEC_PARAMETERS" : {
                            "defaultQueue" : "batch",
                            "environment" : {
                                "blabla" : "blabla2",
                            },
                        },
                    },
                },
                "type" : "parallel_test",
             },
        },
    },

看看这个函数

QJson文档::fromJson(QByteArray)

http://doc.qt.io/qt-5/qjsondocument.html#fromJson

然后使用QJsonDocument::object(),您可以使用密钥获取您的值:

QJsonDocument doc = QJsonDocument::fromJson(QByteArray);
QJsonObject root = doc.object();
foreach(QJsonValue element, root["CELLS"].toArray()){
    QJsonObject node = element.toObject();
    node["whatEver"];
}

如果您的Qt版本>5.5,请检查QJSonDocument,http://doc.qt.io/qt-5/qjsondocument.html.

示例:

    // Just read it from a file... or copy here        
    const QString yourJSON = "...";
    const QJsonDocument jsonDoc = QJsonDocument::fromJson(yourJSON.toLocal8Bit());
    const QVariantMap map = jsonDoc.toVariant().toMap();

要处理CELLS内部的CELLS嵌套,请首先加载CELLS数组:

    // Start read your parameter
    const QVariant testCells2 = map["test_cells2"].toVariant();
    const QVariantList CELLS = testCells2.toList();
    // Now, we have a list available CELLS, check one be one
    foreach (const QVariant& cell, CELLS) {
        const QVariantMap wrapped = cell.toMap();
        qDebug() << "Pretty Name: " << wrapped["prettyName"].toString();
        qDebug() << "Type: " << wrapped["type"].toString();
        const hasList = !wrapped["CELLS"].toList().isEmpty();
        qDebug() << "Has child list? <<  hasList;
        if (hasList) {
             // Start another loop to check the child list.
        }
    }