我正在尝试用 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());
}
}
但是我得到了这样的 map :
"" => z.value
我在Java文档中发现,如果属性.asText()
不是值节点,则它会返回empty
。我怎样才能得到这个名字,所以我的 map 是:
x => x.value
y => y.value
z => z.value
最佳答案
首先您需要 JSON 的 key 。所以我尝试使用 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());
}
我使用字段
的原因是因为我需要键值:
Iterator that can be used to traverse all key/value pairs for object nodes; empty iterator (no contents) for other types
并且 elements
不包含键:
Method for accessing all value nodes of this Node, iff this node is a JSON Array or Object node. In case of Object node, field names (keys) are not included, only values. For other types of nodes, returns empty iterator.
这正在填充 map 。我使用了jackson 2.9.4
关于java - JSON:解析数组的ArrayNode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51307773/