c++ - 在 QT 中解析 JSON 对象中的 JSON 对象

标签 c++ json qt

我正在使用 QT5 尝试解析此 JSON 文件。

格式

{
  "HwDescription": {
    "ConnectionsName": "file://settings/connections_2CBC.xml",
    "ShelveId": "0",
    "BeBoard": {
      "Id": "0",
      "connectionId": "board0",
      "boardType": "GLIB"
    }
  }
}

如您所见,“HwDescription”中有对象。我不知道如何提取它们。我可以很好地进行 1D。

我的尝试

首先我创建对象:

QJsonParseError json_parse_error;
QJsonDocument json_doc = QJsonDocument::fromJson(rawJson.toUtf8(), &json_parse_error);
QJsonObject json_result= json_doc.object();
return std::make_pair(json_result, json_parse_error);

这会返回我的 json_result 作为 QJsonObject - 别担心 - 这部分绝对有效。

使用我的调试器,我可以看到原始 json 确实已被正确传递。所以一个

auto json_obj = json_result.first; //my breakpoint shows me that the data made it this far
//auto connection = json_obj.toObject(); //says there is no member named toObject in QObject

//none of the below methods work

auto test = json_obj["HwDescription","ConnectionsName"].toString();
QJsonArray cmd_array= json_obj["HwDescription"].toArray();
QStringList cmd_list;
for (auto item: cmd_array)
{
    cmd_list.append(item.toString());
}
m_modelCommands.setStringList(cmd_list);

//m_connectionsName = json_obj["HwDescription"].toString(); //this doesn't work either

我知道这是我解析的方式不正确,有人可以快速告诉我哪里出错了吗?然后我也可以为我的 3D 对象执行此操作。

最佳答案

我想你需要这样的东西:

auto json_obj = json_result.first;

QJsonObject obj_HwDescription = json_obj["HwDescription"].toObject();
QString str_ConnectionsName = obj_HwDescription["ConnectionsName"].toString();
// ...
QJsonObject obj_BeBoard = obj_HwDescription["BeBoard"].toObject();
// ...

文档:

关于c++ - 在 QT 中解析 JSON 对象中的 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25789788/

相关文章:

c++ - 使用使基类多态?

c++ - 如何在 C++ 中打印二维数组?

c++ - 使用类属性作为数组绑定(bind)

javascript - 如何使用 JQuery 将 javascript 对象(从 json webmethod 转换)映射到数组,其中 js 对象仅具有 1 个属性和多个值

json - 如何在Jackson中以数组开头反序列化JSON文件?

c++ - QWidget 中的 SDL_Surface

c++ - QList<T>::at 中的 Qt ASSERT 失败:“索引超出范围

python - 如何将 c++ 类包装到 python 以便我可以使用 pybind11 访问其成员的公共(public)方法(成员是对象指针)

c++ - 捕捉 QWidget 真实可见性状态变化

javascript - Python 和 JavaScript 之间的 JSON 日期时间