24

The JSON string is as follows

{
   "rank":"-text_relevance",
   "match-expr":"(label 'star wars')",
   "hits":{
      "found":7,
      "start":0,
      "hit":[
         {"id":"tt1185834",
             "data":{
                "actor":["Abercrombie, Ian","Baker, Dee","Burton, Corey"],
                "title":["Star Wars: The Clone Wars"]
             }
         },
         .
         .
         .
         {"id":"tt0121766",
             "data":{
                "actor":["Bai, Ling","Bryant, Gene","Castle-Hughes, Keisha"],
                "title":["Star Wars: Episode III - Revenge of the Sith"]
             }
         }
       ]
    },
    "info":{
       "rid":"b7c167f6c2da6d93531b9a7b314ad030b3a74803b4b7797edb905ba5a6a08",
       "time-ms":2,
       "cpu-time-ms":0
    }
    } 

It has many fields, but I just have want the Data field. This won't work:

mapper.readvalue(jsonString,Data.class); 

How do I make Jackson read just the "Data" field?

4

3 回答 3

33

Jackson 2.3 现在有一个可以使用的 JsonPointer 类。他们的发布快速概述中有一个简单的示例。

用法很简单:对于 JSON 之类的

{
    "address" : { "street" : "2940 5th Ave", "zip" : 980021 },   
    "dimensions" : [ 10.0, 20.0, 15.0 ] 
}

您可以使用以下表达式:

  JsonNode root = mapper.readTree(src); 
  int zip =root.at("/address/zip").asIntValue(); 
  double height = root.add("/dimensions/1").asDoubleValue();// assuming it's the second number in there
于 2015-07-30T23:08:57.463 回答
15

我认为最简单的方法是使用 Jackson TreeModel:假设对数据结构有一定了解,让 Jackson 将 JSON 输入解析为JsonNode您然后查询的对象。通过这种方式,您可以忽略大部分数据,向下查找JsonNodes您想要的数据。

// String input = The JSON data from your question
ObjectMapper mapper = new ObjectMapper();

JsonNode rootNode = mapper.readValue(input.getBytes(), JsonNode.class); 

// can also use ArrayNode here, but JsonNode allows us to get(index) line an array:
JsonNode hits = rootNode.get("hits");

// can also use ObjectNodes here:
JsonNode oneHit = null;
JsonNode dataObj = null;

int idx = 0;

Data data = null;


if (hits != null)
{
    hits = hits.get("hit");

    if (hits != null)
    {
        while ((oneHit = hits.get(idx)) != null)
        {
            dataObj = oneHit.get("data");
            System.out.println("Data[" + idx + "]: " + dataObj);
            idx++;
        }
    }
}

输出:

 Data[0]: {"id":"tt1185834","data":{"actor":["Abercrombie, Ian","Baker, Dee","Burton, Corey"],"title":["Star Wars: The Clone Wars"]}}
 Data[1]: {"id":"tt0121766","data":{"actor":["Bai, Ling","Bryant, Gene","Castle-Hughes, Keisha"],"title":["Star Wars: Episode III - Revenge of the Sith"]}}

您仍然可以使用您的Data类实现,但我相信这将需要获取String每个代表data- 如上依赖toString或使用JsonNode.getText()- 并使用重新解析它ObjectMapper

mapper.readValue(dataArray, Data.class));

另一种方法是使用杰克逊流模型,并自己拦截节点,直到您看到标记每个data元素开始的输入部分,然后使用字符串并调用objectMapper.readValue每个字符串的内容。

于 2012-07-26T21:08:55.937 回答
5

对于这种要求,Json-path 可能是一个很好的选择 - 如果您对 Jackson 以外的解决方案没问题,那就是:http ://code.google.com/p/json-path/

于 2012-07-27T00:06:49.943 回答