从boost::p roperty_tree读取数组显示为空白
Reading array from boost::property_tree comes up blank
我正在尝试使用此问题中显示的方法从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
相关文章:
- 显示错误输出的简单数组排序程序
- 显示数组中的学生 ID 和最高分
- 代码使用向量成功运行,但使用数组显示错误
- 对象初始化后在C++中显示 char 数组时的异常行为
- 为什么静态数组成员变量在调用对象的实例后不显示任何内容?
- 在命令行上将输入显示到数组中时如何删除 ./a.out?
- 为什么将指针重新分配给 1D 数组的 char 时显示错误,但 2D 数组工作正常?
- 如何在函数中显示结构数组
- 显示结构数组
- 在数组中显示第一个元素用户输入
- 在大小为 10 的 char 数组中输入超过 10 个字符的字符串并输出时,它会显示整个数组而不是前 10 个数组.为什
- 我编写了一个程序来显示数组的内容,但它显示的是它的地址
- 为什么断点显示数组的第二个值是一个大数字?额外学分工作
- 将 5 个 for 循环压缩为,将数组显示为 1
- 为什么析构函数和复制构造函数使用对象数组显示此行为
- 在VC2010中使用Char数组显示字符串时发生运行时错误
- 将数组显示为表格
- 从boost::p roperty_tree读取数组显示为空白
- c++错误数组显示
- 二维动态数组c++显示问题