2016-04-09 84 views
1

試圖將JSON字符串映射到java類,但它不工作。使用傑克遜圖書館,這裏是我的代碼。 輸入JSON:如何將json列表反序列化到傑克遜的java對象

{ 
    "code":"1", 
    "message":"1", 
    "result":[ 
     { 
     "serviceid":"13", 
     "servicename":"service1", 
     "price":"78000", 
     "amount":"2048" 
     }, 
     { 
     "serviceid":"14", 
     "servicename":"service2", 
     "price":"118000", 
     "amount":"3072" 
     } 
    ] 
} 

Java類:

public class serviceList 
{ 
    public int serviceid; 
    public String servicename; 
    public double price; 
    public int amount; 
} 

public class serviceList_result 
{ 
    public String code; 
    public String message; 
    public ArrayList<serviceList> result; 

    public serviceList_result() 
    { 
     result = new ArrayList<serviceList>(); 
    } 

} 

我使用此代碼爲mappling

serviceList_result srv= mapper.readValue(jsonInString, TypeFactory.defaultInstance().constructCollectionType(ArrayList.class,serviceList_result.class)); 

錯誤:

無法反序列化的Java實例。 util.ArrayList出 START_OBJECT

我的代碼有什麼問題?

回答

0

有一個在你的代碼不需要這樣的:

serviceList_result srv= mapper.readValue(jsonInString, TypeFactory.defaultInstance().constructCollectionType(ArrayList.class,serviceList_result.class)); 

有了這個,你說你要反序列化集合,即[ ... ]

相反,簡單地做:

serviceList_result srv= mapper.readValue(json, serviceList_result.class); 

傑克遜庫將弄清楚如何創建類定義serviceList_result對象。

+0

感謝它的工作。 – Oli