Как сгенерировать json с помощью c ++ и повысить библиотеку - PullRequest
1 голос
/ 06 февраля 2020

Я хочу сгенерировать 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);
}

// теперь logi c для создания json

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

// код выше работает нормально, но я хочу добавить через l oop с использованием вектора и динамического добавления данных в поля "id" и "type" массива опций.

1 Ответ

2 голосов
/ 06 февраля 2020

если у вас есть "id", "введите" данные в качестве векторов, вы можете сгенерировать часть "options" вашего 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);
...