Create a json array in C++

Hannes picture Hannes · Apr 17, 2014 · Viewed 62.4k times · Source

So im trying to create a json Object in c++ dynamically. I want to add a timestamp and then an array with the data included.

So thats what my json String would look like :

{
    "timestep": "2160.00",
    "vehicles": [
        {
            "id": "35092_35092_353",
            "x": "6.988270",
            "y": "50.872139",
            "angle": "-20.812787",
            "type": "passenger_P_14_1",
            "speed": "0.000000",
            "pos": "4.600000",
            "lane": "4.600000",
            "slope": "4.600000"
        },
        {
            "id": "35092_35092_353",
            "x": "6.988270",
            "y": "50.872139",
            "angle": "-20.812787",
            "type": "passenger_P_14_1",
            "speed": "0.000000",
            "pos": "4.600000",
            "lane": "4.600000",
            "slope": "4.600000"
        },
        {
            "id": "35092_35092_353",
            "x": "6.988270",
            "y": "50.872139",
            "angle": "-20.812787",
            "type": "passenger_P_14_1",
            "speed": "0.000000",
            "pos": "4.600000",
            "lane": "4.600000",
            "slope": "4.600000"
        }
    ]
}

Im totally new to C++ and im using the Casablanca ( C++ REST SDK) package. So im having a really hard time producing the code. And i cant find any working solutions. I found this on the wiki

Create a JSON object:

json::value obj;
obj[L"key1"] = json::value::boolean(false);
obj[L"key2"] = json::value::number(44);
obj[L"key3"] = json::value::number(43.6);
obj[L"key4"] = json::value::string(U("str"));

and that works for me. But how do i create an array?

i tried several things but nothing worked. Maybe theres a better package? But as far as i understood its an official micorosft package for json and http.

Help would be really nice!

Answer

FatalFlaw picture FatalFlaw · Apr 17, 2014

There are 2 mechanisms. If you are used to std c++ libraries, this should look familiar. Element vector is derived from std::vector.

json::value::element_vector e;
// the first item in the pair is the array index, the second the value
e.push_back(std::make_pair(json::value(0), json::value(false)));
e.push_back(std::make_pair(json::value(1), json::value::string(U("hello"))));
json::value arr(e);

And, if you prefer a cleaner look, and can accept a less efficient compiled result:

json::value arr;
arr[0] = json::value(false);
arr[1] = json::value(U("hello"));

From your message you have tried a bunch of stuff. If you have tried mechanisms like these but they didn't work, give us a sample program that demontrates the failure and we'll have a crack at it.

To get the basic structure in your file above:

json::value vehicles;
vehicles[0] = // 1st vehicle object
vehicles[1] = // 2nd vehicle object
// etc
json::value root;
root[L"timestep"] = json::number(2160.0);
root[L"vehicles"] = vehicles;