我有这个代码,我需要解析/或获取 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
生活在 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
这篇关于使用 Boost ptree 将 JSON 数组解析为 std::string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!