c++ - 如何使用Ct Qt解析此JSON?

标签 c++ qt

我有一个像这样的json:

{
  "name1": {
    "path": "D:/myfolder"
  },
  "name2": {
    "path": "D:/anotherFolder"
  },
  "name3": {
    "path": "D:/myfolder"
  }
}

我想得到:是名称和文件夹名称。
喜欢 :
   name1, D:/myfolder
   name2, D:/anotherFolder
   name3, D:/myfolder

我是独立保存还是在 map 中获取都不重要,因为我想保存它们
将新变量转换为另一个结构。
到目前为止,我有:
QString jsonFile = "myjson.json";
QFile loadFile(jsonFile);

if(!loadFile.open(QIODevice::ReadOnly)){
qDebug() << "Failed to open " << loadFile;    }

QByteArray data = loadFile.readAll();
QJsonDocument loadDoc(QJsonDocument::fromJson(data));

QJsonObject json = loadDoc.object(); 
QStringList keys = json.keys();      // <------- that give me the names. check.

但是我没有得到:如何获得第二个元素?!
到目前为止,最近的方法是使用foreach获得“第二维”:
foreach(const QJsonValue path, json ){
        qInfo() << path;
}

这给了我作为输出:
QJsonValue(object, QJsonObject({"path": "D:/myfolder"}))
QJsonValue(object, QJsonObject({"path": "D:/anotherFolder"}))
QJsonValue(object, QJsonObject({"path": "D:/myfolder"}))

最佳答案

最佳方法是仅使用单个进行迭代

QJsonDocument doc = QJsonDocument::fromJson(data);
QJsonObject json = doc.object();
for (auto it = json.constBegin(); it != json.constEnd(); ++it)
{
    qInfo() << it.key() << it.value().toObject().value("path").toString();
}

关于c++ - 如何使用Ct Qt解析此JSON?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61828574/

相关文章:

c++ - gtkmm textview epands 而不是滚动

c++ - 不同库继承问题中具有相同文件名的类

c++ - 警告 : control reaches end of non-void function in recursive function

qt - QGLWidget 比 QWidget 慢

qt - Qt中如何轻松建立SSH连接?

c++ - 如何用qt获得正确的http文件长度?

c++:解析包含表达式 "access to the multidimensinal array"的字符串

c++ - 无法使用 opengl 正确旋转 2D 对象

c++ - 即使使用另一个线程,启动 while 循环也会卡住程序

c++ - QFileSystemModel rowCount 不能按预期工作