我想浏览下面的json文件并在“坐标”之后保存该部分。
json文件:
{"type": "FeatureCollection","features": [{"type": "Feature","properties": {},"geometry": {"type": "LineString","coordinates": [[4.354282,52.032195],[4.354087,52.032462],[4.353783,52.032962],[4.353579,52.033437],[4.353333,52.034151],[4.352991,52.03545],[4.352517,52.037002],[4.352442,52.037352],[4.352368,52.0378],[4.352336,52.038238],[4.352331,52.039962],[4.352346,52.040706]
]
}
}
] }
我见过使用getJSONArray()和getJSONObject()here和here的代码。这些信息帮助我选择(在我的情况下)“几何”树。
到目前为止我的代码(test2.geojson是上面提到的json文件):
String output = new String(Files.readAllBytes(Paths
.get("C:\\Users\\****\\Desktop\\test2.geojson")));
JSONObject obj = new JSONObject(output);
JSONArray jsonArray = obj.getJSONArray("features");
System.out.println(jsonArray);
但是,这只会重新排列文件并将第一部分附加到文件的末尾。
[{"geometry":{"coordinates":[[4.354282,52.032195],[4.354087,52.032462],[4.353783,52.032962],[4.353579,52.033437],[4.353333,52.034151],[4.352991,52.03545],[4.352517,52.037002],[4.352442,52.037352],[4.352368,52.0378],[4.352336,52.038238],[4.352331,52.039962],[4.352346,52.040706]],"type":"LineString"},"type":"Feature","properties":{}}]
获得所需输出的任何解决方案:
[[4.354282,52.032195],[4.354087,52.032462],[4.353783,52.032962],[4.353579,52.033437],[4.353333,52.034151],[4.352991,52.03545],[4.352517,52.037002],[4.352442,52.037352],[4.352368,52.0378],[4.352336,52.038238],[4.352331,52.039962],[4.352346,52.040706]
]
}
}
] }
提前致谢。 干杯!
答案 0 :(得分:2)
由于“几何”是一个json对象{},“coordinates”是一个json数组[],
你应该这样做
JSONArray jsonArray = obj.getJSONArray("features");
JSONArray resultArray = jsonArray.getJSONObject[0].getJSONObject("geometry").getJSONArray("coordinates")