我正在尝试遍历下面的 JSON 文本。问题是我不知道如何从 Java 中的坐标路径检索坐标数组。采用以下格式经/纬度。我已经包含了一个尝试解析的 JSON 字符串,但是我不确定如何使用 Jackson Functions 遍历该数组。
坐标
"coordinates": {
"type": "Point",
"coordinates": [-82.3248262, 29.6516344]
Java代码
if(root.path("coordinates").path("coordinates").isArray() &&
root.path("coordinates").path("coordinates") != null) {
lat = root.path("coordinates").path("coordinates").get(1).asText();
lon = root.path("coordinates").path("coordinates").get(0).asText();
}
最佳答案
首先,您的 if
条件存在严重错误:
根据Jackson
库,当路径为path()
时,方法path()
返回MissingNode
对象而不是null
未找到,因此您需要相应地修复 if
条件。
由于 MissingNode
是 Jackson
数据类型,因此对 MissingNode
的检查是多余的,您只需检查它是否为 >ArrayNode
.
This method is similar to get(String), except that instead of returning null if no such value exists (due to this node not being an object, or object not having value for the specified field), a "missing node" (node that returns true for isMissingNode()) will be returned.
其次,要迭代ArrayNode
,您可以执行以下操作:
if (root.path("coordinates").path("coordinates").isArray()) {
lat = root.path("coordinates").path("coordinates").get(1).asText();
lon = root.path("coordinates").path("coordinates").get(0).asText();
}
关于Java - 遍历数组节点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35156777/