2

我是读/写 JSON 文件的初学者。如何在读取创建的 JSON 后将std::vector<std::vector<Point>>(C++ 数据类型)写入 JSON 文件,以便可以单独访问每个文件?std::vector<point>请帮忙。

4

3 回答 3

3

假设一个 POD 数据结构,您可以使用以下命令对其进行序列化:

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);
}

生成的 JSON 是:

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

您可以将其作为数组数组访问,就像在 C++ 中一样。

于 2014-07-08T14:39:42.300 回答
1

@Sga 的答案是正确的,但它缺少写入文件的内容,因此我将使用写入文件的行报告他的代码(我更改了一些名称)。

polys在我的例子中是一个 openCV 对象向量的向量,Point但它不会改变任何东西。

Json::Value polygons(Json::arrayValue);
std::ofstream file_id;
file_id.open(dataFileName);
Json::StyledWriter styledWriter;

for (size_t i = 0; i != polys.size(); i++)
{
    Json::Value singlePoly(Json::arrayValue);

    for (size_t j = 0; j != polys.at(i).size(); j++)
    {
        Json::Value pointSingle(Json::objectValue);
        pointSingle["x"] = polys.at(i).at(j).x;
        pointSingle["y"] = polys.at(i).at(j).y;
        singlePoly.append(pointSingle);
    }

    polygons.append(singlePoly);
}
file_id << styledWriter.write(polygons);

file_id.close();
于 2018-09-11T08:18:01.530 回答
0

您的 JSON 应如下所示:

{
  "vectorVectors" : [
    { 
      "pointVectors" : [
        { "point": "<some representation of a point>" },
        // ...
      ]
    },
    // ... 
  ]
}

vectorVectors就是您VectorsVector<Point>s 列表,pointVectors是其中的一个单独元素Vector(包含多个Vector<Point>s),并且point是您的 a 的实际表示Point

至于如何生成这个布局,看起来你也许可以使用rapidjson,但我不确定——我从未使用过它。

于 2014-07-08T14:41:55.587 回答