使用Jackson读取JSON字符串的一部分

JSON字符串如下

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

它有很多字段,但我只想要数据字段。 这不起作用:

 mapper.readvalue(jsonString,Data.class); 

如何让jackson只阅读“数据”字段?

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 

我认为最简单的方法是使用Jackson TreeModel :让jackson将JSON输入解析为一个JsonNode对象,然后再进行查询,假设有一些数据结构知识。 这样,您可以忽略大多数数据,沿着JsonNodes向下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类实现,但我相信这将需要获取表示每个dataString – 如上所述依赖于toString ,或使用JsonNode.getText() – 并使用ObjectMapper重新解析它:

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

另一种方法是使用Jackson Streaming Model,并自己拦截节点,直到看到标记每个data元素开头的输入部分,然后使用字符串并为每个字符串调用objectMapper.readValue

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