c++ - 使用 boost 属性树读取 int 数组

我有一些带有一些整数数组变量的 JSON,如下所示:

{"a": [8, 6, 2], "b": [2, 2, 1]}

我想使用 boost property_tree,例如:

std::stringstream ss;
boost::property_tree::ptree pt;

ss << "{\"a\": [8, 6, 2], \"b\": [2, 2, 1]}";

boost::property_tree::read_json(ss, pt);
std::vector<int> a = pt.get<std::vector<int> >("a");

这不起作用,我尝试过的 int 指针也没有任何变化。如何从属性树中读取数组?

最佳答案

JSON 支持, boost 属性树参差不齐。

The property tree dataset is not typed, and does not support arrays as such. Thus, the following JSON / property tree mapping is used:

  • JSON objects are mapped to nodes. Each property is a child node.
  • JSON arrays are mapped to nodes. Each element is a child node with an empty name. If a node has both named and unnamed child nodes, it cannot be mapped to a JSON representation.
  • JSON values are mapped to nodes containing the value. However, all type information is lost; numbers, as well as the literals "null", "true" and "false" are simply mapped to their string form.
  • Property tree nodes containing both child nodes and data cannot be mapped.

(来自documentation)

您可以使用辅助函数迭代数组。

#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/json_parser.hpp>

using boost::property_tree::ptree;

template <typename T>
std::vector<T> as_vector(ptree const& pt, ptree::key_type const& key)
{
    std::vector<T> r;
    for (auto& item : pt.get_child(key))
        r.push_back(item.second.get_value<T>());
    return r;
}

int main()
{
    std::stringstream ss("{\"a\": [8, 6, 2], \"b\": [2, 2, 1]}");

    ptree pt;
    read_json(ss, pt);

    for (auto i : as_vector<int>(pt, "a")) std::cout << i << ' ';
    std::cout << '\n';
    for (auto i : as_vector<int>(pt, "b")) std::cout << i << ' ';
}

Live On Coliru 。输出:

8 6 2 
2 2 1

https://stackoverflow.com/questions/23481262/

相关文章:

json - 如何解析/反序列化动态 JSON

json - 我可以使用哪些程序来可视化 JSON 文件?

json - LibreOffice Calc 是否支持 JSON 文件导入/排序?

java - 如何防止 Gson 将长数字(一个 json 字符串)转换为科学记数法格式?

json - 转义正则表达式以获取有效的 JSON

java - 如何使用 gson 调用默认反序列化

java - 规范化 JSON 文件

php - 添加json文件注释

javascript - Sequelize - 如何仅返回数据库结果的 JSON 对象?

c# - 在 JSON 反序列化期间没有为 'System.String' 类型定义无参数构造函数