0

If I have

{
     "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"
                   }
              }
          ]
    }
}

How can I extract only the list of sources but using a simple ObjectMapper method? I do not want to process by myself every node.

Almo
  • 15,538
  • 13
  • 67
  • 95
Roxana
  • 1,569
  • 3
  • 24
  • 41

2 Answers2

2

I suppose the valid json is like

{
  "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"
    }
      }
    ]
  }
}

If so you can get it as

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>>() {});
Syam S
  • 8,421
  • 1
  • 26
  • 36
  • I want this values to be automatically transformed to a java object. like the mapper does for the normal situations. – Roxana Aug 08 '14 at 13:39
  • Possible.. Say you have a class Source. Then you could use converValue method. Updated my answer.. – Syam S Aug 08 '14 at 13:50
0

You can try with 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);
Ruchira Gayan Ranaweera
  • 34,993
  • 17
  • 75
  • 115