QT读取JSON文件并存储和检索值
QT Reading a JSON file and storing and retriving values
我正在尝试读取如下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.
}
}
相关文章:
- 使用 pqxx 将 std::vector 存储在 postgresql 中,并从数据库中检索它
- C++-需要读取存储在文件(.txt)中的时间戳并正确检索
- 我正在编写一个代码来将 int 数组存储在文件中,然后用 c++ 检索它,但是检索第一项是假值,我该如何解决这个问题?
- SQLite3 C++检索 ID 并存储到另一个表
- 如何在文件中节省空间地存储和检索 std::vector<int> 值
- 如何从 linux 二进制文件中存储和检索数据
- 如何将浮子值的字节存储在字符串中并以后检索值
- 如何在三维数组中使用std::map来存储/检索具有特定值的键
- 存储和检索位字段中的有符号值
- 如何通过先前存储的ID从结构对象中检索值?C
- 手动检索和存储指向 OpenGL 函数的指针时遇到问题
- c++使用字符串句柄对对象进行通用存储和检索
- 使用 XPTR 在内存中存储和检索矩阵
- 以数组的形式存储组合框项,并在 WPF 中检索 SelectedId
- 使用 QSqlQuery 检索 MySQL 存储过程的输出
- 使用c++通过文件存储和检索链表
- 从数据库中以 blob 数据类型形式存储的原始图像数据中检索 CImage 对象
- 从矢量中存储和检索IplImages
- 使用自动 c++ 检索存储元组的值
- 如何检索存储在列表中的一对点