json – 用gson反序列化泛型

我正在使用GSON 1.4,并使用两个通用的数组列表< myObject>序列化对象如下
String data = Gson.toJson(object,object.class).当我想要它,我做gson.fromJson(json,type);

可惜我得到了

java.lang.IllegalArgumentException: Can not set java.util.ArrayList
field … to 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;
}
最佳答案
由于Java的类型擦除,Gson对于集合有一些限制.你可以阅读更多关于它here.

从你的问题我看到你正在使用ArrayList和LinkedList.你确定你不是仅仅使用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);

转载注明原文:json – 用gson反序列化泛型 - 代码日志