从boost::p roperty_tree读取数组显示为空白

Reading array from boost::property_tree comes up blank

本文关键字:数组 显示 读取 空白 boost roperty tree      更新时间:2023-10-16

我正在尝试使用此问题中显示的方法从boost::property_tree读取数组数据。 在该示例中,数组首先作为字符串读取,转换为字符串流,然后读入数组。 在实施该解决方案时,我注意到我的字符串为空。

示例输入 (json):

"Object1"
{
  "param1" : 10.0,
  "initPos" :
  {
    "":1.0,  
    "":2.0, 
    "":5.0 
  },
  "initVel" : [ 0.0, 0.0, 0.0 ]
}

这两种数组表示法都由 boost json 解析器解释为数组。 我相信数据存在于属性树中,因为在调用 json 编写器时,数组数据存在于输出中。

这是失败的示例:

std::string paramName = "Object1.initPos";
tempParamString = _runTree.get<std::string>(paramName,"Not Found");
std::cout << "Value: " << tempParamString << std::endl;

paramName "Object1.param1"时,我得到字符串形式的"10.0"输出,当paramName "Object1.initPos"时,我得到一个空字符串,如果paramName是树中不存在的内容,则返回"Not Found"

首先,确保提供的 JSON 有效。看起来它有一些问题。接下来,您无法获取 Object1.initPos 作为字符串。它的类型是boost::p roperty_tree::p tree。您可以使用get_child获取它并对其进行处理。

#include <algorithm>
#include <string>
#include <sstream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp> 
using namespace std;
using namespace boost::property_tree;
int _tmain(int argc, _TCHAR* argv[])
{
    try
    {
        std::string j("{ "Object1" : { "param1" : 10.0, "initPos" : { "":1.0, "":2.0, "":5.0 }, "initVel" : [ 0.0, 0.0, 0.0 ] } }");
        std::istringstream iss(j);
        ptree pt;
        json_parser::read_json(iss, pt);
        auto s = pt.get<std::string>("Object1.param1");
        cout << s << endl; // 10
        ptree& pos = pt.get_child("Object1.initPos");
        std::for_each(std::begin(pos), std::end(pos), [](ptree::value_type& kv) { 
            cout << "K: " << kv.first << endl;
            cout << "V: " << kv.second.get<std::string>("") << endl;
        });
    }
    catch(std::exception& ex)
    {
        std::cout << "ERR:" << ex.what() << endl;
    }
    return 0;
}

输出:

10.0
K:
V: 1.0
K:
V: 2.0
K:
V: 5.0