小编典典

用gson反序列化泛型

json

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

可悲的是我得到了

java.lang.IllegalArgumentException:无法将java.util.ArrayList字段…设置为java.util.LinkedList

这是为什么 ?GSON文档指出,如果我使用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;
}

阅读 657

收藏
2020-07-27

共1个答案

小编典典

由于Java的类型擦除,Gson在集合方面有一些限制。您可以在此处了解更多信息。

从您的问题中,我看到您同时使用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);
2020-07-27