首页 > 解决方案 > 如何使用 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”字段中动态添加。

标签: c++jsonboost

解决方案


如果您将“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);

推荐阅读