Google Gson - deserialize list object? (generic type)

前端 未结 13 2098
灰色年华
灰色年华 2020-11-22 09:42

I want to transfer a list object via Google Gson, but I don\'t know how to deserialize generic types.

What I tried after looking at this (BalusC\'s answer):

13条回答
  •  心在旅途
    2020-11-22 10:00

    Method to deserialize generic collection:

    import java.lang.reflect.Type;
    import com.google.gson.reflect.TypeToken;
    
    ...
    
    Type listType = new TypeToken>(){}.getType();
    List yourClassList = new Gson().fromJson(jsonArray, listType);
    

    Since several people in the comments have mentioned it, here's an explanation of how the TypeToken class is being used. The construction new TypeToken<...>() {}.getType() captures a compile-time type (between the < and >) into a runtime java.lang.reflect.Type object. Unlike a Class object, which can only represent a raw (erased) type, the Type object can represent any type in the Java language, including a parameterized instantiation of a generic type.

    The TypeToken class itself does not have a public constructor, because you're not supposed to construct it directly. Instead, you always construct an anonymous subclass (hence the {}, which is a necessary part of this expression).

    Due to type erasure, the TypeToken class is only able to capture types that are fully known at compile time. (That is, you can't do new TypeToken>() {}.getType() for a type parameter T.)

    For more information, see the documentation for the TypeToken class.

提交回复
热议问题