Search code examples
c++arraysjsoncasablanca

Create a JSON array in C++


I'm trying to create a JSON object in C++ dynamically. I want to add a timestamp and then an array with the data included.

This is 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"
        }
    ]
}

I'm totally new to C++ and I'm using the Casablanca (C++ REST SDK) package. I'm 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 there's a better package? But as far as I understood it's an official Microsoft package for JSON and HTTP.


Solution

  • 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;