gpt4 book ai didi

json - 使用 gson 反序列化泛型

转载 作者:行者123 更新时间:2023-12-03 21:26:59 26 4
gpt4 key购买 nike

我正在使用 GSON 1.4 并使用两个通用 arraylist<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 文档指出,如果我使用 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 .

从你的问题我看到你同时使用 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)改成了这个,这样我就不用和其他类(class)混了:
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 反序列化泛型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4364392/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com