user414977
user414977

Reputation: 275

how to parse json (from elasticsearch) into array without the meta info

{
  "took": 3,
  "timed_out": false,
  "_shards": {
    "total": 5,
    "successful": 5,
    "failed": 0
  },
  "hits": {
    "total": 2,
    "max_score": 1.0,
    "hits": [
      {
        "_index": "contacts",
        "_type": "index",
        "_id": "2",
        "_score": 1.0,
        "_source": {
          "id": "c201",
          "name": "Johnny Depp",
          "phone": {
            "mobile": "+91 0000000000",
            "home": "00 000000"
          }
        }
      }
    ]
  }
}

I have a elasticsearch json object to use in my application. I do not want to use the elasticsearch api. Also need to strip off the meta info, could you please advise

Upvotes: 0

Views: 5651

Answers (1)

rednoyz
rednoyz

Reputation: 1327

This answer assumes you are using the org.json package and that the hits array only has one element (otherwise you need to loop over hitsArr):

JSONObject json = new JSONObject(jsonString);
JSONObject hitsObj = json.getJSONObject("hits");
JSONArray hitsArr = hitsObj.getJSONArray("hits");
JSONObject first = hitsArr.getJSONObject(0); // assumes 1 entry in hits array
JSONObject source = first.getJSONObject("_source");
JSONObject phone = source.getJSONObject("phone");

String id = source.getString("id");
String name = source.getString("name");
String mobile = phone.getString("mobile");
String home = phone.getString("home");

System.out.println(id + "\n" + name + "\n" + mobile + "\n" +home);

Upvotes: 4

Related Questions