使用 NLOHMANN JSON 在 C++ 中创建嵌套的 JSON 对象
creating nested json object in c++ using nlohmann json
我正在使用 https://github.com/nlohmann/json,它运行良好。但是我发现很难创建以下json输出
{
"Id": 1,
"Child": [
{
"Id": 2
},
{
"Id": 3,
"Child": [
{
"Id" : 5
},
{
"Id" : 6
}
]
},
{
"Id": 4
}
]
}
每个节点都必须有一个 id 和一个数组("子"元素(。任何子项都可以递归地继续具有 Id 或子项。上面的 json 只是一个示例。我想要的是使用 nlohmann json 在父节点和子节点之间创建一个链。
数字 1, 2, 3, ....是随机捡到的。我们现在不关心这些价值观。
知道如何创建它吗?
到目前为止的代码
#include <iostream>
#include <string>
#include <vector>
#include "json.hpp"
using json = nlohmann::json;
struct json_node_t {
int id;
std::vector<json_node_t> child;
};
int main( int argc, char** argv) {
json j;
for( int i = 0; i < 3; i++) {
json_node_t n;
n.id = i;
j["id"] = i;
if ( i < 2 ) {
j["child"].push_back(n);
}
}
return 0;
}
为了序列化你自己的类型,你需要为该类型实现一个to_json
函数。
#include <iostream>
#include <string>
#include <vector>
#include "json.hpp"
using namespace std;
using json = nlohmann::json;
struct json_node_t {
int id;
std::vector<json_node_t> child;
};
void to_json(json& j, const json_node_t& node) {
j = {{"ID", node.id}};
if (!node.child.empty())
j.push_back({"children", node.child});
}
int main() {
json_node_t node = {1, {{2, {}}, {3, {{5, {}}, {6, {}}}}, {4, {}}}};
json j = node;
cout << j.dump(2) << endl;
return 0;
}
输出:
{
"ID": 1,
"children": [
{
"ID": 2
},
{
"ID": 3,
"children": [
{
"ID": 5
},
{
"ID": 6
}
]
},
{
"ID": 4
}
]
}
还有几种初始化json_node_t
的方法(都产生相同的树和相同的输出(:
struct json_node_t {
int id;
std::vector<json_node_t> child;
json_node_t(int node_id, initializer_list<json_node_t> node_children = initializer_list<json_node_t>());
json_node_t& add(const json_node_t& node);
json_node_t& add(const initializer_list<json_node_t>& nodes);
};
json_node_t::json_node_t(int node_id, initializer_list<json_node_t> node_children) : id(node_id), child(node_children) {
}
json_node_t& json_node_t::add(const json_node_t& node) {
child.push_back(node);
return child.back();
}
json_node_t& json_node_t::add(const initializer_list<json_node_t>& nodes) {
child.insert(child.end(), nodes);
return child.back();
}
int main() {
json_node_t node_a = {1, {{2, {}}, {3, {{5, {}}, {6, {}}}}, {4, {}}}};
json_node_t node_b = {1, {2, {3, {5, 6}}, 4}};
json_node_t node_c(1);
node_c.add(2);
node_c.add(3).add({5, 6});
node_c.add(4);
cout << json(node_a).dump(2) << endl << endl;
cout << json(node_b).dump(2) << endl << endl;
cout << json(node_c).dump(2) << endl;
return 0;
}
相关文章:
- 嵌套在类中时无法设置成员数据
- 无法访问嵌套类.类的使用无效
- 我正在使用嵌套的while循环来解析具有多行的文本文件,但由于某种原因,它只通过第一行,我不知道为什么
- 如何在C++中初始化嵌套类中的2个memeber
- 如何声明特征矩阵,然后通过嵌套循环初始化它
- 在C++中搜索嵌套多映射值
- 在C++中将矢量转换为嵌套地图
- C++嵌套if语句,基本货币交换
- 在nlohmann json中,如何将嵌套对象的数组转换为嵌套结构的向量
- UE4 C++ 我无法将 JSON 嵌套值获取到 TArray
- 获取嵌套的 JSON 数组和矩阵C++
- 使用 NLOHMANN JSON 在 C++ 中创建嵌套的 JSON 对象
- Poco 迭代嵌套的 JSON 对象
- 在 Qt 中解析嵌套的 JSON 时出现意外结果(数组不存在)
- 如何在 C++ 中使用 JSON CPP 编写嵌套 JSON
- 使用 rapidjson 读取嵌套 Json
- 解析嵌套JSON与QJsonDocument在Qt
- 如何使用json11库在json中添加子/嵌套元素
- 如何在C++中使用 Rapidjson 获取嵌套的 JSON 值
- 虚幻引擎4中的C++嵌套JSON