我正在尝试在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",
},
},
},
答案 0 :(得分:3)
看看这个功能
QJsonDocument :: 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"];
}
答案 1 :(得分:1)
如果你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.
}
}