Deserializing json array using gson

前端 未结 4 1423
深忆病人
深忆病人 2020-12-16 18:34

Continuing from this question.

I\'m having trouble deserializing the following json array (Sorry for the size):

\"geometry\": { \"type\": \"Polygon\"         


        
4条回答
  •  孤城傲影
    2020-12-16 19:36

    According to Gson user guide:

    Serializing and Deserializing Generic Types
    When you call toJson(obj), Gson calls obj.getClass() to get information about the fields to serialize. Similarly, you can typically pass MyClass.class object in the fromJson(json, MyClass.class) method. This works fine as long as the object is a non-generic type. However, if the object is of a generic type, then the generic type information is lost because of Java Type Erasure. Here is an example illustrating the point:

    List myStrings = new List();
    gson.toJson(myStrings); // Will cause a runtime exception
    
    gson.fromJson(json, myStrings.getClass());
    

    The above call results in a runtime exception because Gson invokes myStrings.getClass() to get its class information, but this method returns a raw class, List.class. This means that Gson has no way of knowing that this is a list of Strings, and not plain objects.

    You can solve this problem by specifying the correct parameterized type for your generic type. You can do this by using the TypeToken class.

    Type listType = new TypeToken>() {}.getType();
    gson.toJson(myStrings, listType);
    
    gson.fromJson(json, listType);
    

    The idiom used to get listType actually defines an anonymous local inner class containing a method getType() that returns the fully parameterized type.

    Hope this helps.

提交回复
热议问题