如何使用 c++ 和提升库生成 json

How to generate json with c++ and boost library

本文关键字:json 何使用 c++      更新时间:2023-10-16

我想以以下格式生成 json,并且我已经编写了如下代码,因为我是 C++ 的初学者,所以我想以更有效的方式完成相同的操作。

{
"id": "0001",
"type": "donut",
"name": "cake",
"ppu": "0.55",
"option":
{
"options":
[
{
"id": "5001",
"type": "furniture"
},
{
"id": "5002",
"type": "furniture2"
},
{
"id": "5003",
"type": "furniture3"
}
]
},
"Grid":
[
{
"id": "5001",
"type": "furniture"
},
{
"id": "5002",
"type": "furniture2"
},
{
"id": "5003",
"type": "furniture3"
},
{
"id": "5004",
"type": "furniture4"
}
]
}

我有以下代码用于生成的 JSON

generateJson(){
boost::property_tree::ptree members,members1,child,child1,child2,child3,children,options,option;
anotherStructName c;
members.put<string>("id","0001");
members.put<string>("type","donut");
members.put<string>("name","cake");
members.put<double>("ppu",0.55);
children.push_back(std::make_pair("",child));
children.push_back(std::make_pair("",child1));
children.push_back(std::make_pair("",child2));
children.push_back(std::make_pair("",child3));
option.push_back(std::make_pair("",child));
option.push_back(std::make_pair("",child1));
option.push_back(std::make_pair("",child2));
options.put_child("option",batter);
members.put_child("options",options);
members.add_child("Grid",children);
return c.createJsonString(members);
}

创建 JSON 的逻辑

string anotherStructName::createJsonString(boost::property_tree::ptree json)
{
std::stringstream jsonString;
write_json(jsonString, json);
return jsonString.str();
}

上面的代码工作正常,但我想通过循环添加它,在选项数组的"id"和"type"字段中使用矢量和数据动态添加。

如果你有"id","type"数据作为向量,你可以像这样生成json的"选项"部分

vector<string> id, type;
boost::property_tree::ptree options, option;
for (int i = 0; i < id.size() && i < type.size(); ++i) {
boost::property_tree::ptree child;
child.put<string>("id",id[i]);
child.put<string>("type",type[i]);
options.push_back(std::make_pair("",child));
}
option.put_child("options",options);