【发布时间】:2014-07-08 10:41:38
【问题描述】:
我是读/写 JSON 文件的初学者。
如何将std::vector<std::vector<Point>>(C++ 数据类型)写入 JSON 文件,以便在读取创建的 JSON 后分别访问每个std::vector<point>?
请帮忙。
【问题讨论】:
我是读/写 JSON 文件的初学者。
如何将std::vector<std::vector<Point>>(C++ 数据类型)写入 JSON 文件,以便在读取创建的 JSON 后分别访问每个std::vector<point>?
请帮忙。
【问题讨论】:
@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();
【讨论】:
假设一个 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++ 中一样。
【讨论】:
您的 JSON 应该如下所示:
{
"vectorVectors" : [
{
"pointVectors" : [
{ "point": "<some representation of a point>" },
// ...
]
},
// ...
]
}
这样vectorVectors 是Vector<Point>s 的Vectors 列表,pointVectors 是Vector 的一个单独元素(包含多个Vector<Point>s),point 是实际表示给你一个Point。
至于如何生成这个布局,看起来你可以使用rapidjson,但我不确定——我从未使用过。
【讨论】:
jsoncpp 标记了这个问题,这是一个特定的 C++ JSON 库