2012-04-15 95 views
2

我有json,我試圖用Jackson解析。 JSON看起來像 -解析動態json

coupons: { 
    1: { 
    title: "Mode von", 
    description: "", 
    type: "offer", 
    code: "-", 
    expiry: "0000-00-00", 
    link: "" 
    },  
    2: { 
    title: "Prime 1", 
    description: "", 
    type: "offer", 
    code: "-", 
    expiry: "0000-00-00", 
    link: "http://test.com/" 
    } 
} 

優惠券的數量在這裏不是恆定的,並且會根據響應而變化。 我的兩難困境是創建相應的java類,它可以容納這樣的對象。

我試着用地圖爲 -

public class Coupons { 
    Map<String, String>coupons = new HashMap<String, String>(); 
    public Map<String, String> getCoupons() { 
     return coupons; 
    } 
} 

但是 -

System.out.println(coupons.getCoupons().get("type")); 
System.out.println(coupons.getCoupons().get("code")); 

總是讓我空。這個json的java class是什麼?

回答

2

您的第一級密鑰是索引號1,2,3等 所以爲了獲得類型和代碼,您必須指定密鑰。

你可以這樣做:

var coupons = coupons.getCoupons(); //<--breakpoint to see if this is really populated. 
foreach(String key in coupons.Keys){ //<- pseudo code, iterate over keys 
    var obj = coupons.get(key); 
    var type = obj.get("type"); 
    etc.. 
} 

希望這可以幫助你前進

+0

我覺得我不能只是做 - '地圖優惠券=新的HashMap ( );'as'coupons.getCoupons()'不會給我任何Map對象 – Tarun 2012-04-15 16:34:37

+0

好的,我將地圖改爲 - 'private Map > coupons = new HashMap >();'但解決方案的關鍵是按照您的建議獲取地圖的關鍵點。 – Tarun 2012-04-15 17:01:48