2010-12-06 154 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