从JSONObject数据获取字段内容

时间:2019-07-12 12:50:19

标签: java elasticsearch

我想从String JsonData中获取以“ target”开头的“ hits Array”中的内容,如下所示, 我从elasticsearch服务器获得了JSONData,

String holdedEntity = 
{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 5,
    "successful" : 5,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : 1,
    "max_score" : 1.0,
    "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"
        }

我尝试过此方法,但如上所述无法给出正确的结果,请提出任何建议,我将非常感谢,

JSONObject jsonObj = new JSONObject(holdedEntity);//convert the holdedEntity into JSONObject.

JSONObject jsonObjectContent = jsonObj.getJSONObject("target");//trying to get the content starting from "target" until the "text" .

String result = jsonObjectContent.toString(); //converting the jsonObjectContent  toString.

但是它无法识别字段“目标”并抛出失败,

JSONObject["target"] not found

请提出任何建议。

1 个答案:

答案 0 :(得分:0)

顶层没有target字段;您必须先获取hits字段,然后是 that 的{{11}}字段,然后是 that 的适当元素(因为它是一个数组) ;最后,那个hits元素将为您带来所需的结果。