2011-12-22 71 views
2

我想用Jackson解析JSON Bing的結果,但我對如何使用它有點困惑。這裏是從Bing收到的JSON的一個例子:解析Jackson的JSON Bing結果

{ 
    "SearchResponse":{ 
     "Version":"2.2", 
     "Query":{ 
     "SearchTerms":"jackson json" 
     }, 
     "Web":{ 
     "Total":1010000, 
     "Offset":0, 
     "Results":[ 
      { 
       "Title":"Jackson JSON Processor - Home", 
       "Description":"News: 04-Nov-2011: Jackson 1.9.2 released; 23-Oct-2011: Jackson 1.9.1 released; 04-Oct-2011: Jackson 1.9.0 released (@JsonUnwrapped, value instantiators, value ...", 
       "Url":"http:\/\/jackson.codehaus.org\/", 
       "CacheUrl":"http:\/\/cc.bingj.com\/cache.aspx?q=jackson+json&d=4616347212909127&w=cbaf5322,11c785e8", 
       "DisplayUrl":"jackson.codehaus.org", 
       "DateTime":"2011-12-18T23:12:00Z", 
       "DeepLinks":"[...]" 
      } 
     ] 
     } 
    } 
} 

我真的只需要結果數組中的數據。這個數組可以有從0到n的任何結果。有人可以舉例說明如何使用Jackson來反序列化「結果」?

回答

10

首先,將您的JSON讀取爲一棵樹。實例化一個ObjectMapper並使用readTree()方法讀取您的JSON。

這會給你一個JsonNode。通過陣列抓住結果作爲另一個JsonNode和週期:

final ObjectMapper mapper = new ObjectMapper(); 

final JsonNode input = mapper.readTree(...); 

final JsonNode results = input.get("SearchResponse").get("Web").get("Results"); 

/* 
* Yes, this works: JsonNode implements Iterable<JsonNode>, and this will 
* cycle through array elements 
*/ 
for (final JsonNode element: results) { 
    // do whatever with array elements 
} 

你也可以考慮驗證使用JSON模式實現您的輸入。無恥插件:https://github.com/fge/json-schema-validator

+0

'results'看起來並不像一個集合,但你似乎來遍歷它。 – 2011-12-22 23:16:11

+1

是的,因爲'JsonNode'實現'Iterable '。在容器(即對象或數組)上調用時,它將循環訪問數組元素(數組)或屬性值(對象)。在另一個JSON節點類型上,基礎迭代器是空的。 – fge 2011-12-22 23:17:15

+0

爲什麼你實例化ObjectMapper,然後靜態引用它? – nagytech 2013-09-08 05:18:48

3

fge的答案是如果你想直接使用傑克遜的方法。

如果你想在基於json的pojos上工作,那麼你可以嘗試json2pojo(https://github.com/wotifgroup/json2pojo-我無恥的插件:))把你的示例json並生成java類。

假設你調用頂層類「兵」,那麼你可以使用這樣的代碼:

final ObjectMapper mapper = new ObjectMapper(); 

final Bing bing = ObjectMapper.readValue(..., Bing.class); 

/* 
* you may need a null check on getResults depending on what the 
* Bing search returns for empty results. 
*/ 
for (Result r : bing.getSearchResponse().getWeb().getResults()) { 
    ... 
} 
+0

非常酷的額外件 - 感謝分享。看起來像是傑克遜數據綁定的好夥伴! – StaxMan 2011-12-23 18:06:33