0
{
  "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

4
  • And what is the "meta info" in the JSON above? Also, what do you want to do with the JSON once you have "cleaned it up"? And which JSON API do you use? Commented Apr 8, 2014 at 10:18
  • I need to use this in my android app, for a start I just need to store as a key value pair from the above example I just need "id": "c201", "name": "Johnny Depp", , "phone": { "mobile": "+91 0000000000", "home": "00 000000", } } Commented Apr 8, 2014 at 10:19
  • Then you just need to get member "_source" from the initial JSON Object. I take it you use org.json as bundled by android? Commented Apr 8, 2014 at 10:22
  • Also, what if there are several answers? How is the JSON in this case? You could consider using JSON Path Commented Apr 8, 2014 at 10:24

1 Answer 1

4

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.