deserializing generics with gson

前端 未结 1 769
清歌不尽
清歌不尽 2020-12-03 21:31

I am using GSON 1.4 and serializing an object with two generic arraylist as follows String data = Gson.toJson(object, object.class)

相关标签:
1条回答
  • 2020-12-03 22:14

    Gson has some limitations regarding collections because of Java's type erasure. You can read more about it here.

    From your question I see you're using both ArrayList and LinkedList. Are you sure you didn't mean to use just List, the interface?

    This code works:

    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);
    

    Update: I changed your class to this, so I don't have to mess around with other classes:

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

    And using this code, everything works for me:

    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);
    
    0 讨论(0)
提交回复
热议问题