使用 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") << "
";
std::cout << "number: " << pt.get<std::string>("number") << "
";
for (auto& e : pt.get_child("stuff")) {
std::cout << "stuff name: " << e.second.get<std::string>("name") << "
";
}
}
印刷品
id: 123
number: 456
stuff name: test
stuff name: some
stuff name: stuffs
相关文章