使用Boost ptree将JSON数组解析为std :: string [英] Parse JSON array as std::string with Boost ptree

查看:386
本文介绍了使用Boost ptree将JSON数组解析为std :: string的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此代码,我需要解析/或将JSON数组作为std :: string使用在应用程序中.

I have this code that I need to parse/or get the JSON array as std::string to be used in the app.

std::string ss = "{ \"id\" : \"123\", \"number\" : \"456\", \"stuff\" : [{ \"name\" : \"test\" }] }";

ptree pt2;
std::istringstream is(ss);
read_json(is, pt2);
std::string id = pt2.get<std::string>("id");
std::string num= pt2.get<std::string>("number");
std::string stuff = pt2.get<std::string>("stuff"); 

需要的是像这样的"std :: string [{ "name" : "test" }]

What is needed is the "stuff" to be retrieved like this as std::string [{ "name" : "test" }]

但是,stuff上面的代码只是返回空字符串.有什么问题

However the code above stuff is just returning empty string. What could be wrong

推荐答案

数组表示为具有许多""键的子节点:

Arrays are represented as child nodes with many "" keys:

文档

docs

  • JSON数组映射到节点.每个元素都是一个空名称的子节点.如果节点同时具有已命名和未命名的子节点,则无法将其映射到JSON表示形式.

在Coliru上直播

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

using boost::property_tree::ptree;

int main() {
    std::string ss = "{ \"id\" : \"123\", \"number\" : \"456\", \"stuff\" : [{ \"name\" : \"test\" }, { \"name\" : \"some\" }, { \"name\" : \"stuffs\" }] }";

    ptree pt;
    std::istringstream is(ss);
    read_json(is, pt);

    std::cout << "id:     " << pt.get<std::string>("id") << "\n";
    std::cout << "number: " << pt.get<std::string>("number") << "\n";
    for (auto& e : pt.get_child("stuff")) {
        std::cout << "stuff name: " << e.second.get<std::string>("name") << "\n";
    }
}

打印

id:     123
number: 456
stuff name: test
stuff name: some
stuff name: stuffs

这篇关于使用Boost ptree将JSON数组解析为std :: string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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