如何在没有元信息的情况下将json(从elasticsearch)解析为数组

时间:2014-04-08 10:14:42

标签: java json elasticsearch

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

我有一个在我的应用程序中使用的elasticsearch json对象。我不想使用elasticsearch api。还需要剥离元信息,请你指教

1 个答案:

答案 0 :(得分:3)

这个答案假设您正在使用org.json包并且hits数组只有一个元素(否则您需要遍历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);