Java中的Json:如何提取子元素列表?

时间:2014-08-08 12:22:18

标签: java json jackson

如果我有

{
     "took": 4,
     "timed_out": false,
     "hits": {
          "total": 14,
          "max_score": 1,
          "hits": [
             {
                "_index": "someIndex",
                "_source": {
                   "id": "de",
                   "title": "something 1"
                   },
                "_index": "someIndex",
                "_source": {
                   "id": "def",
                   "title": "something 1"
                   }
              }
          ]
    }
}

如何仅使用简单的ObjectMapper方法提取源列表?我不想每个节点自己处理。

2 个答案:

答案 0 :(得分:2)

我认为有效的json就像

{
  "took": 4,
  "timed_out": false,
  "hits": {
    "total": 14,
    "max_score": 1,
    "hits": [
      {
    "_index": "someIndex",
    "_source": {
      "id": "de",
      "title": "something 1"
    }
      },
      {
    "_index": "someIndex",
    "_source": {
      "id": "def",
      "title": "something 1"
    }
      }
    ]
  }
}

如果是这样,你可以把它作为

ObjectMapper mapper = new ObjectMapper();
JsonNode data = mapper.readTree(json);
data.findValues("_source"); // [{"id":"de","title":"something 1"}, {"id":"def","title":"something 1"}]
//If you want to convert it to custom object
List<Source> sources = mapper.convertValue(data.findValues("_source"), new TypeReference<List<Source>>() {});

答案 1 :(得分:0)

您可以尝试使用JsonPath

 List<String> sources = JsonPath.read("{\n" +
                "\n" +
                "    \"took\":4,\n" +
                "    \"timed_out\":false,\n" +
                "    \"hits\":{\n" +
                "        \"total\":14,\n" +
                "        \"max_score\":1,\n" +
                "        \"hits\":[\n" +
                "            {\n" +
                "                \"_index\":\"someIndex\",\n" +
                "                \"_source\":{\n" +
                "                    \"id\":\"def\",\n" +
                "                    \"title\":\"something 1\"\n" +
                "                }\n" +
                "            }\n" +
                "        ]\n" +
                "    }\n" +
                "\n" +
                "}", "$.hits.hits[*]._source[*]");
        System.out.println(sources);