Google Gson - deserialize list object? (generic type)

前端 未结 13 2085
灰色年华
灰色年华 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 09:57

    I liked the answer from kays1 but I couldn't implement it. So I built my own version using his concept.

    public class JsonListHelper{
        public static final <T> List<T> getList(String json) throws Exception {
            Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
            Type typeOfList = new TypeToken<List<T>>(){}.getType();
            return gson.fromJson(json, typeOfList);
        }
    }
    

    Usage:

    List<MyClass> MyList= JsonListHelper.getList(jsonArrayString);
    
    0 讨论(0)
  • 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<ArrayList<YourClass>>(){}.getType();
    List<YourClass> 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<List<T>>() {}.getType() for a type parameter T.)

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

    0 讨论(0)
  • 2020-11-22 10:01

    Since Gson 2.8, we can create util function like

    public <T> List<T> getList(String jsonArray, Class<T> clazz) {
        Type typeOfT = TypeToken.getParameterized(List.class, clazz).getType();
        return new Gson().fromJson(jsonArray, typeOfT);
    }
    

    Example using

    String jsonArray = ...
    List<User> user = getList(jsonArray, User.class);
    
    0 讨论(0)
  • 2020-11-22 10:02
    public static final <T> List<T> getList(final Class<T[]> clazz, final String json)
    {
        final T[] jsonToObject = new Gson().fromJson(json, clazz);
    
        return Arrays.asList(jsonToObject);
    }
    

    Example:

    getList(MyClass[].class, "[{...}]");
    
    0 讨论(0)
  • 2020-11-22 10:02

    Here is a solution that works with a dynamically defined type. The trick is creating the proper type of of array using Array.newInstance().

        public static <T> List<T> fromJsonList(String json, Class<T> clazz) {
        Object [] array = (Object[])java.lang.reflect.Array.newInstance(clazz, 0);
        array = gson.fromJson(json, array.getClass());
        List<T> list = new ArrayList<T>();
        for (int i=0 ; i<array.length ; i++)
            list.add(clazz.cast(array[i]));
        return list; 
    }
    
    0 讨论(0)
  • 2020-11-22 10:07

    For Kotlin simply:

    import java.lang.reflect.Type
    import com.google.gson.reflect.TypeToken
    ...
    val type = object : TypeToken<List<T>>() {}.type
    

    or, here is a useful function:

    fun <T> typeOfList(): Type {
        return object : TypeToken<List<T>>() {}.type
    }
    

    Then, to use:

    val type = typeOfList<YourMagicObject>()
    
    0 讨论(0)
提交回复
热议问题