如何使用C ++

时间:2015-08-08 20:30:54

标签: c++ json boost

我知道如何解析"正常"查看JSON中的C++数据。通常,我使用boost::property_treeread_json方法执行此操作。它可能看起来像这样:

BOOST_FOREAH(ptree::value_type &v, pt.get_child("rows"){
    vec.push_back(v.second.get<std::string>("key"));
}

,上面的代码对应于这个JSON文件:

{
    "rows":[{
         "key":"1"
     },{
         "key":"2"
     }]
}

但是,我得到的Neo4j结果集如下:

{
    "columns":{...},
    "data":[[["object 1"]], [["object 2"]], [["object 3"]]]
}

我感兴趣并希望解析"data"节点。我试着这样做:

BOOST_FOREAH(ptree::value_type &v, pt.get_child("data"){
    vec.push_back(v.second.data());
}

但这不起作用。我没有收到错误,但我的矢量vec仍为空,或者更确切地说,它填充了空值。所以,当我遍历这个vec时,我看到了许多元素,但它们没有任何价值。鉴于,我希望值为"object 1""object 2""object 3"

2 个答案:

答案 0 :(得分:2)

解决方案如下所示:

using boost::property::ptree;
ptree pt;
//... populate ptree pt with data from some source
BOOST_FOREACH(ptree::value_type &v, pt.get_child('data')){
    ptree subtree1 = v.second;
    BOOST_FOREACH(ptree::value_type &vs, subtree1){
        ptree subtree2 = vs.second;
        BOOST_FOREACH(ptree::value_type &vs2, subtree2){
            do_something(vs2.second.data());
        }
    }
}

此代码可以解析此类JSON结构:

{
 "data":[[["object 1"]], [["object 2"]], [["object 3"]]]
}

因此,与某些人所说的相反,实际上,没有必要使用其他第三方库。仅使用boost即可完成。

答案 1 :(得分:0)

这是我如何做的一个例子。您必须提前知道JSON结构。

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

boost::property_tree::ptree pt, sub_pt;
std::string json_str, key, sub_key;
std::stringstream ss;
int value = 0, bus_num = 0;

json_str = "{\"arduino_1\": {\"bus_1\": 17425,\"bus_2\": 1025,\"bus_3\": 0,\"bus_4\": 0,\"bus_5\": 0,\"bus_6\": 0,\"bus_7\": 0,\"bus_8\": 0}}";


ss << json_str; // put string into stringstream
boost::property_tree::read_json(ss, pt);    // put stringstream into property tree
for (boost::property_tree::ptree::iterator iter = pt.begin(); iter != pt.end(); iter++)
{
    // get data
    key = boost::lexical_cast <std::string>(iter->first.data());
    sub_pt = iter->second;

    // iterate over subtree
    for (boost::property_tree::ptree::iterator sub_iter = sub_pt.begin(); sub_iter != sub_pt.end(); sub_iter++)
    {
        // get data
        sub_key = boost::lexical_cast <std::string>(sub_iter->first.data());
        value = boost::lexical_cast <int>(sub_iter->second.data());
    }
}