2012-08-02 59 views
0

對於 -GSON(JSON)解析 - POJO映射 - 錯誤(這不是一個JSON陣列)

Config rfqObj = new Gson().fromJson(data, new TypeToken<Config>() {}.getType()); 

,我發現了以下情況例外 -

的JsonDeserializer main[email protected]30de3c87 失敗以反序列化的json對象{}給定類型 [email protected]]和根 原因java.lang.IllegalStateException: This is not a JSON Array

JSON數據 -

{ 
    "quantities": { 
    "142": "0", 
    "143": "20", 
    "144": "25" 
    }, 
    "characteristics": {}, 
    "details": { 
    "8": "HT Test Report", 
    "9": "Others", 
    "13": "nTest" 
    }, 
    "materials": {}, 
    "additionalProcesses": {}, 
    "suppliers": {} 
} 

這裏是POJO -

public class Config { 
Map<Long, String> quantities = new HashMap<Long, String>(); 
Map<Long, String> characteristics = new HashMap<Long, String>();  
Map<Long, String> details = new HashMap<Long, String>(); 
Map<Long, String> materials = new HashMap<Long, String>(); 
Map<Long, String> additionalProcesses = new HashMap<Long, String>(); 

public Set<Suppliers> suppliers = new HashSet(); 

//this is for the nested class 
public static class Suppliers { 
    // defining attributes of this class 
    public Long id; 
    public String name; 
    public Long contactId; 
    public String contactInfo; 
    public String contactMethod; 
    public String contactName; 
    public String message; 
} 
} 
+0

您是否知道哪些組件導致故障?供應商領域是一套嗎?看起來這些集合會序列化成數組而不是對象。 – 2012-08-02 14:14:07

+0

這是供應商。那麼如何讓它序列化爲對象呢? – wichita 2012-08-05 01:50:41

+0

你有一組供應商,所以當你序列化這個集合時,你會得到'[]'空集,而不是'{}'。如果你有兩個供應商,你會看到'[{...},{...}]'。 – 2012-08-05 03:01:41

回答

0

你所得到的錯誤的原因是,你的JSON文本是一個具有以下屬性的對象:

"suppliers": {} 

但是因爲您的Config對象需要屬性suppliers爲一組; Gson期待JSON數組,而不是JSON對象。

如果你能以某種方式讓你的JSON文本,包括

"suppliers": [] 

,你應該能夠反序列化到Java集合這一點。