如何使用 c++ 和提升库生成 json
How to generate json with c++ and boost library
我想以以下格式生成 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);
相关文章:
- 在c++中使用nlohmann从类到json的转换
- 如何使用curlpp通过POST方法上传文件和json数据
- 使用 jsoncpp 解析 json 数组字符串
- 将 FlatBuffer 对象序列化为 JSON,而不使用其架构文件
- 使用 cmake 生成 compile_commands.json
- 如何使用 c++ 和提升库生成 json
- 使用 minijson-reader 库读取 JSON 字符串时出现问题
- 使用 Qt 解析 JSON 数组
- 如何使用 picojson.h 在 c++ 中从头开始创建 json 对象
- 使用 QT 逐行读取 JSON
- 无法使用 Poco 库正确克隆 JSON 数组C++
- 如何在 C++ 中使用提升属性树从 JSON 文件中读取对象数组
- 从Qt QJsonDocument::toBinaryData使用non-Qt读取Binary Json?
- 如何使用基于范围的for循环迭代Rapidjson文档(它本身就是一个JSON数组)
- 我正在使用快速 JSON 为C++回合制 RPG 解析对象敌人,并且遇到了一些奇怪的错误
- 使用 NLOHMANN JSON 在 C++ 中创建嵌套的 JSON 对象
- 使用 jsoncpp 读取 JSON 文件
- 快速JSON如何使用字符串变量查询对象
- C Nlohmann/JSON如何使用运行时提供JSON_POINTERS读取JSON值
- Json解析使用rapidJson在c++中给出错误