【问题标题】:Boost ptree node for all children in a json array为 json 数组中的所有子节点提升 ptree 节点
【发布时间】:2014-12-15 12:58:38
【问题描述】:

我一直在寻找这个问题的答案,但是如果之前有人问过这个问题,我找不到任何很抱歉的东西。我有以下 json 文件

{"GuiComponents": [
{
    "GuiComponent":
    {
        "screen": "WindowMain",
        "type": "class Robot",
        "filename": "robot.mesh",
        "blueprint": "Betplacement/Robot.json",
        "layer": "0",
        "position": 
        {
            "x": "0",
            "y": "0"
        }
    }
},
{
    "GuiComponent": 
    {
        "screen": "WindowTop",
        "type": "class Robot",
        "filename": "robot.mesh",
        "blueprint": "Betplacement/Robot.json",
        "layer": "0",
        "position": 
            {
            "x": "0",
            "y": "0"
            }
        }
    }
]
}   

现在我想遍历 GuiComponents 中名为 GuiComponent 的所有子节点,并将每个子节点分配给一个 ptree 节点。这样,我可以简单地将 ptree 节点传递给任何想要获取特定 GuiComponent 的数据而无需查看所有其他子节点的人。我找不到使用 get_child 执行此操作的方法,因为它只会引发“No such node GuiComponent”异常。

任何帮助将不胜感激。

谢谢

【问题讨论】:

  • 您能否提供一个示例,说明您如何尝试使用get_child() 访问节点?
  • 我试过 boost::property_tree::ptree child = m_tree.get_child("GuiComponents.GuiComponent") 和 boost::property_tree::ptree child = m_tree.get_child("GuiComponent")。谢谢

标签: c++ json boost boost-propertytree


【解决方案1】:

您的GuiComponent 元素存储在数组的未命名元素中;读取 JSON 数据时,Boost.PropertyTree 会"translate" array elements into children of empty nodes

您可以尝试以下操作:搜索空节点,然后使用 equal_range() 方法在每个节点内搜索元素 GuiComponent

auto array_iter = m_tree.equal_range("");
for (auto i: array_iter) {
  auto gui_iter = i->second.equal_range("GuiComponent");
  for (auto gui_component: gui_iter) {
    // ...
  }
}

ptree 上的迭代器指向一对,其中第一个元素是节点的名称,第二个元素是 ptree。

【讨论】:

  • 不返回任何有用的东西。 result.first 等于 result.second。塔
  • @codetemplar 我已经更新了我的答案:由于您的 JSON 数据中有一个数组,ptree 将其转换为未命名的节点。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多