首页 > 解决方案 > 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

标签: javaarraysjsonparsing

解决方案


首先,您需要 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


推荐阅读