2010-12-06 144 views
13

我正在使用GSON 1.4并使用两个通用arraylist<myObject>序列化一个对象,如下所示 String data = Gson.toJson(object, object.class)。当我desirialize是我做的gson.fromJson(json, type);使用gson反序列化泛型

可悲的是,我得到

java.lang.IllegalArgumentException异常:无法设置的java.util.ArrayList 场......到java.util.LinkedList中

这是为什么? GSON doc指出,如果我使用object.class参数序列化,它支持泛型。任何想法?谢谢。

我的课是:

public class IndicesAndWeightsParams { 

    public List<IndexParams> indicesParams; 
    public List<WeightParams> weightsParams; 

    public IndicesAndWeightsParams() { 
     indicesParams = new ArrayList<IndexParams>(); 
     weightsParams = new ArrayList<WeightParams>(); 
    } 
    public IndicesAndWeightsParams(ArrayList<IndexParams> indicesParams, ArrayList<WeightParams> weightsParams) { 
     this.indicesParams = indicesParams; 
     this.weightsParams = weightsParams; 
    } 
}  
public class IndexParams { 

    public IndexParams() { 
    } 
    public IndexParams(String key, float value, String name) { 
     this.key = key; 
     this.value = value; 
     this.name = name; 
    } 
    public String key; 
    public float value; 
    public String name; 
} 

回答

22

GSON有关于因为Java的类型擦除的集合一定的局限性。你可以阅读更多关于它here

从你的问题我看你正在使用ArrayListLinkedList。你确定你不是只想用List这个界面吗?

此代码:

List<String> listOfStrings = new ArrayList<String>(); 

listOfStrings.add("one"); 
listOfStrings.add("two"); 

Gson gson = new Gson(); 
String json = gson.toJson(listOfStrings); 

System.out.println(json); 

Type type = new TypeToken<Collection<String>>(){}.getType(); 

List<String> fromJson = gson.fromJson(json, type); 

System.out.println(fromJson); 

更新:我改变你的类这一点,所以我没有浪费时间与其他类:

class IndicesAndWeightsParams { 

    public List<Integer> indicesParams; 
    public List<String> weightsParams; 

    public IndicesAndWeightsParams() { 
     indicesParams = new ArrayList<Integer>(); 
     weightsParams = new ArrayList<String>(); 
    } 
    public IndicesAndWeightsParams(ArrayList<Integer> indicesParams, ArrayList<String> weightsParams) { 
     this.indicesParams = indicesParams; 
     this.weightsParams = weightsParams; 
    } 
} 

并使用此代码,一切适用于我:

ArrayList<Integer> indices = new ArrayList<Integer>(); 
ArrayList<String> weights = new ArrayList<String>(); 

indices.add(2); 
indices.add(5); 

weights.add("fifty"); 
weights.add("twenty"); 

IndicesAndWeightsParams iaw = new IndicesAndWeightsParams(indices, weights); 

Gson gson = new Gson(); 
String string = gson.toJson(iaw); 

System.out.println(string); 

IndicesAndWeightsParams fromJson = gson.fromJson(string, IndicesAndWeightsParams.class); 

System.out.println(fromJson.indicesParams); 
System.out.println(fromJson.weightsParams); 
+0

嗨,感谢您的帮助。我的对象不是通用的,而是包含两个数组列表。我应该如何使用这种类型?
类型类型=新TypeToken (){} getTrype不工作:-( – Jeb 2010-12-06 09:31:51