gpt4 book ai didi

java - 在 Java 中使用 getJSONArray() 和 getJSONObject() 从 JSON 文件获取元素

转载 作者:行者123 更新时间:2023-12-02 04:34:17 26 4
gpt4 key购买 nike

我想浏览下面的 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() 的代码 herehere 。这些信息帮助我选择(在我的例子中)“几何”树。

到目前为止我的代码(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]
]
}
}

]}

提前致谢。干杯!

最佳答案

由于“几何”是一个json对象{},“坐标”是一个json数组[],

你应该这样做

JSONArray jsonArray = obj.getJSONArray("features");
JSONArray resultArray = jsonArray.getJSONObject[0].getJSONObject("geometry").getJSONArray("coordinates")

关于java - 在 Java 中使用 getJSONArray() 和 getJSONObject() 从 JSON 文件获取元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31028698/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com