使用 NLOHMANN JSON 在 C++ 中创建嵌套的 JSON 对象

creating nested json object in c++ using nlohmann json

本文关键字:JSON 嵌套 创建 对象 C++ NLOHMANN 使用      更新时间:2023-10-16

我正在使用 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;
}