用gson反序列化泛型

时间:2010-12-06 08:14:09

标签: json generics gson

我正在使用GSON 1.4并使用两个通用arraylist<myObject>序列化对象,如下所示 String data = Gson.toJson(object, object.class)。当我绝望时,我会gson.fromJson(json, type);

遗憾的是我得到了

  

java.lang.IllegalArgumentException:无法设置java.util.ArrayList   field ...到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;
}

1 个答案:

答案 0 :(得分:23)

由于Java的类型擦除,Gson对集合有一些限制。您可以阅读更多相关信息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);