如何从JSONObject数据的特定字段中获取内容

时间:2019-07-15 11:27:33

标签: java elasticsearch

我想从此JSONObject Data中获取字段“ _source”的内容,

JSONObject jsonObj =   
{  
    "hits" : [
      {
        "_index" : "try1",
        "_type" : "_doc",
        "_id" : "1",
        "_score" : 1.0,
        "_source" : {
          "target" : {
            "br_id" : 0,
            "wo_id" : 2,
            "process" : [
              "element 1",
              "element 2"
            ]
          },
          "explanation" : {
            "an_id" : 1311,
            "pa_name" : "micha"      
          },
          "text" : "hello world"
        }
      }
    ]
}

结果应该像下面这样,

String result = 
{      
          "target" : {
            "br_id" : 0,
            "wo_id" : 2,
            "process" : [
              "element 1",
              "element 2"
            ]
          },
          "explanation" : {
            "an_id" : 1311,
            "pa_name" : "micha"      
          },
          "text" : "hello world"
        }

我尝试过此方法,但始终无法识别“ _source”字段,

            JSONObject main = jsonObj.getJSONObject("hits");
            JSONObject content = main.getJSONObject("_source");
            JSONObject field = content.getJSONObject("target");         

JSONObject["_source"] not found
JSONObject["target"] not found

请提出任何建议或建议,以便我可以从“ _source”获取内容作为结果? 谢谢。

1 个答案:

答案 0 :(得分:1)

_source在JSONArray hits内部,因此首先获取JSONArray

 JSONArray main = jsonObj.getJSONArray("hits");

然后从数组中获取第一个JSONObject

JSONObject obj = main.getJSONObject(0);
JSONObject source = obj.getJSONObject("_source");  //now get the _source