java - JSON:解析数组的ArrayNode

标签 java arrays json parsing

我正在尝试用 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.

来自Java Docs

这正在填充 map 。我使用了jackson 2.9.4

关于java - JSON:解析数组的ArrayNode,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51307773/

相关文章:

javascript - D3 中父/子层次结构中的多级映射可能吗?

java - 使用 Jersey 将传入的 JSON 转换为 Java 数组

java - java : email with pdf attached file : no object DCH for MIME type application/pdf

java - Strings[][] 获取 int 的值

javascript - 遍历对象数组生成d3桑基图数据

python - JSON解码错误 : Expecting value: line 1 column 1 (char 0) error

java - SimpleDateFormat 的 ThreadLocal 变量(或)新的 SimpleDateFormat - 正确吗?

java - 如何使用 spring mvc 在 REST POST 方法中传递 List<>

返回数组的php pdo Select语句,该数组用于再次查询数据库

javascript - 有没有办法 "merge"数组内的两个对象?