注意:实际上不支持顶级数组(您不能使用 Boost Property Tree 来回往返)。
限制在the documentation中描述
保存同一棵树将丢失所有类型信息并将数组转换为:
{
"": {
"a": "5855925.424944928",
"b": "0",
"c": "96",
"d": "2096640",
"e": "0"
}
}
数组是“具有空键的对象”。从您的样本来看,您似乎已经知道这一点。所以,就用它吧:
for (auto& object_node : boost::make_iterator_range(jsontree.equal_range(""))) {
ptree const& object = object_node.second;
std::cout << "a: " << object.get<double>("a") << "\n";
std::cout << "b: " << object.get<int>("b") << "\n";
std::cout << "c: " << object.get<int>("c") << "\n";
std::cout << "d: " << object.get<int>("d") << "\n";
std::cout << "e: " << object.get<int>("e") << "\n";
}
改进的演示
提取一些类型/函数通常会更好:
Live On Coliru
#include <iostream>
#include <boost/property_tree/json_parser.hpp>
using boost::property_tree::ptree;
struct Object {
double a;
int b, c, d, e;
friend std::ostream& operator<<(std::ostream& os, Object const& object) {
return os << "a: " << object.a << "\n"
<< "b: " << object.b << "\n"
<< "c: " << object.c << "\n"
<< "d: " << object.d << "\n"
<< "e: " << object.e << "\n";
}
static Object parse(ptree const& from) {
return {
from.get<double>("a"),
from.get<int>("b"),
from.get<int>("c"),
from.get<int>("d"),
from.get<int>("e"),
};
}
};
int main() {
boost::property_tree::ptree jsontree;
{
std::stringstream ss(R"([{"a": 5855925.424944928, "b": 0, "c": 96, "d": 2096640, "e": 0}])");
boost::property_tree::read_json(ss, jsontree);
}
for (auto& object_node : boost::make_iterator_range(jsontree.equal_range(""))) {
std::cout << Object::parse(object_node.second);
}
}
打印
a: 5.85593e+06
b: 0
c: 96
d: 2096640
e: 0