GSON(JSON)解析 - POJO映射 - 错误(这不是一个JSON阵列)

问题描述:

对于 -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

你所得到的错误的原因是,你的JSON文本是一个具有以下属性的对象:

"suppliers": {} 

但是因为您的Config对象需要属性suppliers为一组; Gson期待JSON数组,而不是JSON对象。

如果你能以某种方式让你的JSON文本,包括

"suppliers": [] 

,你应该能够反序列化到Java集合这一点。