Parse JSON array as std::string with Boost ptree(使用 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
这篇关于使用 Boost ptree 将 JSON 数组解析为 std::string的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用 Boost ptree 将 JSON 数组解析为 std::string
基础教程推荐
- c++ STL设置差异 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
