How to write Vector of Vector of Points in a json file?

json, jsoncpp

Solution

Assuming a POD data structure, you can serialize it with:

struct Point
{
    double x, y;
};

Point p;
p.x = 123;
p.y = 456;

std::vector<Point> arr;
arr.push_back(p);

std::vector<std::vector<Point>> container;
container.push_back(arr);
container.push_back(arr);

Json::Value root(Json::arrayValue);
for (size_t i = 0; i != container.size(); i++)
{
    Json::Value temp(Json::arrayValue);

    for (size_t j = 0; j != container[i].size(); j++)
    {
        Json::Value obj(Json::objectValue); 
        obj["x"] = container[i][j].x;
        obj["y"] = container[i][j].y;
        temp.append(obj);
    }

    root.append(temp);
}

Resulting JSON is:

[
   [
      {
         "x" : 123.0,
         "y" : 456.0
      }
   ],
   [
      {
         "x" : 123.0,
         "y" : 456.0
      }
   ]
]

which you can access as an array of arrays, pretty much as in C++.

Problem

I am a beginner in reading/writing JSON files. How can I write a `std::vector<std::vector<Point>>` (C++ data type) to a JSON file, such that I can access each `std::vector<point>` seperately, after reading the created JSON? Please help.

Original source