如何在java中将特定的Json元素检索到数组中

时间:2016-10-17 11:47:00

标签: java json elasticsearch

我从Elasticsearch返回了以下json。在Java中,将highlight.name值检索到List<String>的最快最有效的方法是什么?

{
      "timed_out": false,
      "_shards": {
        "total": 5,
        "successful": 5,
        "failed": 0
      },
      "hits": {
        "max_score": 6.512624,
        "hits": [
          {
            "_index": "shops",
            "_type": "shop",
            "_id": "AVfRy7_-rRRgqtjX0fQt",
            "_score": 6.512624,
            "highlight": {
              "name": [
                " <em>Smartwatch</em> Phone"
              ]
            }
          },
          {
            "_index": "shops",
            "_type": "shop",
            "_id": "AVfRy7_9rRRgqtjX0fGz",
            "_score": 6.446859,
            "highlight": {
              "name": [
                " <em>Smartwatch</em>"
              ]
            }
          },
          {
            "_index": "shops",
            "_type": "shop",
            "_id": "AVfRy7_-rRRgqtjX0fVa",
            "_score": 3.7999475,
            "highlight": {
              "name": [
                " 3G <em>Smartphone</em>"
              ]
            }
          }
        ]
      }
    }

4 个答案:

答案 0 :(得分:1)

使用JSONObject:

    // jsonResult is a string that contains your ES response
    JSONArray json = (new JSONObject(jsonResult)).getJSONObject("hits").getJSONArray("hits");

    List<JSONArray> result = new ArrayList<>();
    json.forEach((j) -> {
        JSONObject highlight = ((JSONObject) j).getJSONObject("highlight");
        result.add(highlight.getJSONArray("name"));
    });

    // Outputs [[" <em>Smartwatch<\/em> Phone"], [" <em>Smartwatch<\/em>"], [" 3G <em>Smartphone<\/em>"]]
    System.out.println(result);

答案 1 :(得分:0)

杰克逊图书馆提供简单的json格式。

ObjectMapper om = new ObjectMapper();
om.enable(SerializationConfig.Feature.INDENT_OUTPUT);
Object json = om.readValue( output, Object.class );
System.out.println( objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(json));

答案 2 :(得分:0)

您必须对备选方案进行基准测试,以确定哪种方法对您的用例更快,更“高效”(无论如何)。以下可能比通过杰克逊更快,但由于使用正则表达式更脆弱。

cd <<your test folder>>
which chromedriver
chromedriver --version  

答案 3 :(得分:0)

你可以使用jsonPath库,它是在一行代码中从json读取值的最快方法。

List<String> highlightResults = JsonPath.parse(/*yourJsonString*/).read("$..name", List.class);