如何使用c ++和boost库生成json

问题描述 投票:1回答:1

我想以以下格式生成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++ json boost
1个回答
2
投票

如果您将“ 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);
© www.soinside.com 2019 - 2024. All rights reserved.