c++ - 如何使用 c++ 和 boost 库生成 json
问题描述
我想以以下格式生成 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 的“options”部分
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);
推荐阅读
- netlogo - netlogo - 随机转发 -
- javascript - 如何将 DataTables 的本地化更改为德语
- jenkins - 如何启用多字符串参数和文件参数,基于之前在 Jenkins 中的参数选择?
- bash - 如何编写一个bash脚本来计算一个文件夹的所有文件的前n个字节的md5和
- java - Javers.commit() 不工作 MANAGED_CLASS_MAPPING_ERROR
- audio-recording - 如何实现 Nvidia ShadowPlay 之类的录音
- performance - Neo4j 加载 csv 性能问题
- python-3.x - “无法加载本机 TensorFlow 运行时。” 在 cpu 张量流中
- gcc - 从 TCL 执行 cpp/exe
- java - Jackson ObjectMapper 在转换为 POJO 时会忽略某些键