使用boost属性树读取int数组 [英] Using boost property tree to read int array

查看:230
本文介绍了使用boost属性树读取int数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些JSON整数数组变量屈指可数,像这样:

I have some JSON with a handful of integer array variables, like so:

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

我想用升压property_tree,例如:

I would like to use boost property_tree, for instance:

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指针的任何变化。我如何可以读取从属性树数组?

This doesn't work, nor does any variation on an int pointer that I've tried. How may I read an array from a property tree?

推荐答案

JSON支持,是参差不齐与提升属性树。

JSON support, is spotty with boost property tree.

属性树数据集没有输入,不支持数组本身。因此,下面的JSON /属性树映射用于:

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


      
  • JS​​ON对象映射到节点。每个属性是一个子节点。

  •   
  • JS​​ON数组被映射到节点。每个元素都是具有空名称的子节点。如果一个节点都命名和无名子节点,它不能被映射到一个JSON重新presentation。

  •   
  • JS​​ON值被映射到包含该值的节点。然而,所有的类型信息被丢失;号,以及文字空,真和假被简单地映射到它们的字符串的形式。

  •   
  • 同时包含子节点和数据属性树节点不能映射。

  •   

(从<一href=\"http://www.boost.org/doc/libs/1_55_0/doc/html/boost_propertytree/parsers.html#boost_propertytree.parsers.json_parser\">documentation)

您可以用迭代一个辅助函数的数组。

You can iterate the array with a helper function.

#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 << ' ';
}

看它的 住在Coliru 。输出:

See it Live On Coliru. Output:

8 6 2 
2 2 1

这篇关于使用boost属性树读取int数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆