我正在研究java API,我需要将一些数据格式化为JSON。我想要以下结构:
{
"main": {
"point1": {
"x": 0.18,
"y": 10.8,
"z": 0
},
"point2": {
"x": 0.18,
"y": 9.36,
"z": 0
},
"point3": {
"x": 0.18,
"y": 8.46,
"z": 0
},
"point4": {
"x": 0.18,
"y": 7.38,
"z": 0
}
}
}
基本上,“main”JSONObject对象中有一个点列表,但我不希望它是一个数组。
JSONObject main = new JSONObject();
for(Point p : points){
JSONObject point = new JSONObject();
JSONObject coordinates = new JSONObject();
coordinates.put("x", p.getX());
coordinates.put("y", p.getY());
coordinates.put("z", p.getZ());
point.put(p.getName(),coordinates);
main.put("main", point);
}
我使用上面的代码得到以下结果:
{
"main": {
"point4": {
"x": 0.18,
"y": 7.38,
"z": 0
}
}
}
我在最后一行使用的put方法是覆盖以前的点,所以我最后只在主对象中得到一个点。我想我的问题的解决方案是微不足道的,但我无法找到它。
你能帮帮我吗?
答案 0 :(得分:0)
您可以使用原始for
循环。
JSONObject main = new JSONObject();
for(int i = 0; i < points.length; i++){
JSONObject coordinates = new JSONObject();
coordinates.put("x", points[i].getX());
coordinates.put("y", points[i].getY());
coordinates.put("z", points[i].getZ());
main.put("point" + i, coordinates);
}
答案 1 :(得分:0)
你快到了。
通过将每个点添加为单独的字段,将所有点累积到单个JSON对象中:
JSONObject main = new JSONObject();
List<Point> points = new ArrayList<>();
points.add(new Point("point1", 1, 2, 3));
points.add(new Point("point2", 2, 3, 4));
JSONObject pointsAsJson = new JSONObject();
for (Point p : points) {
JSONObject coordinates = new JSONObject();
coordinates.put("x", p.getX());
coordinates.put("y", p.getY());
coordinates.put("z", p.getZ());
pointsAsJson.put(p.getName(), coordinates);
}
main.put("main", pointsAsJson);