14

私は GSON 1.4 を使用しており、次のように 2 つのジェネリックを使用してオブジェクトをシリアル化してarraylist<myObject>います String data = Gson.toJson(object, object.class)。私がそれをデシリアライズするときgson.fromJson(json, type);

悲しいことに、私は得る

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;
}
4

1 に答える 1

23

Gson には、Java の型消去のため、コレクションに関していくつかの制限があります。詳細については、こちらをご覧ください。

あなたの質問から、 と の両方ArrayListを使用していることがわかりますLinkedListListインターフェイスだけを使用するつもりはありませんでしたか?

このコードは機能します:

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);
于 2010-12-06T08:51:13.863 に答える