java - JSON:解析数组的 ArrayNode
问题描述
我正在尝试用 Java 解析 JSON ArrayNode,但遇到了一些问题。
对象如下:
{
"type": "type",
"id": "id",
"attributes": {
"x": [ "x.value" ],
"y": [ "y.value" ],
"z": [ "z.value" ]
}
}
我解析如下:
Map<String, Map<String, String>> users = new HashMap<>();
Iterator<JsonNode> arrayIterator = dataArray.elements();
while (arrayIterator.hasNext())
{
JsonNode r = arrayIterator.next();
String id = r.get("id").asText();
users.put(id, new HashMap<>());
Iterator<JsonNode> attributeIterator = r.path("attributes").elements();
while (attributeIterator.hasNext())
{
JsonNode attribute = attributeIterator.next();
users.get(id).put(attribute.asText(),
attribute.elements().next().asText());
}
}
但我得到一张这样的地图:
"" => z.value
我在 Java 的文档中发现,如果属性不是值节点,.asText()
它将返回。empty
我怎样才能得到这个名字,所以我的地图是:
x => x.value
y => y.value
z => z.value
解决方案
首先,您需要 JSON 的密钥。所以我尝试了fields
而不是仅elements
Iterator<Map.Entry<String, JsonNode>> attributeIterator = dataArray.path("attributes").fields();
while (attributeIterator.hasNext())
{
Map.Entry<String, JsonNode> attribute = attributeIterator.next();
users.get(id).put(attribute.getKey(),
attribute.getValue().get(0).asText());
}
我不喜欢得到一个数组所以我改成这个
Iterator<Map.Entry<String, JsonNode>> attributeIterator = dataArray.path("attributes").fields();
while (attributeIterator.hasNext())
{
Map.Entry<String, JsonNode> attribute = attributeIterator.next();
users.get(id).put(attribute.getKey(),
attribute.getValue().elements().next().textValue());
}
我使用的原因fields
是因为我需要键值:
可用于遍历对象节点的所有键/值对的迭代器;其他类型的空迭代器(无内容)
并且elements
不包括键:
访问该Node的所有value节点的方法,如果该节点是JSON Array或者Object节点。在对象节点的情况下,不包括字段名称(键),仅包括值。对于其他类型的节点,返回空迭代器。
来自Java 文档
这正在填满地图。我用了jackson 2.9.4
推荐阅读
- java - 保存到存储时 PNG 文件大小会增加
- javascript - 在javascript中按字母顺序对数组进行排序
- module - 更改后 Google Colab 中的模块未更新
- android - RedCorners.ExifLibrary.ImageFile 和 ExifInterface GPS 数据始终为零
- javascript - 你好。我想在反应中下载文件...我遇到了这个错误:Uncaught DOMException: Failed to set the 'value'
- javascript - 您可以更改 window.localStorage.setItem() 在某个网页上的工作方式吗?
- matlab - 如何生成视频中的速度场?
- google-cloud-platform - gcloud 构建提交中缺少未知值
- r - 如何使用邮政编码绘制叶绿素图?
- r - 如何根据管道运算符替换向量的元素