Google Gson - deserialize list object? (generic type)

前端 未结 13 2086
灰色年华
灰色年华 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:24

    Another way is to use an array as a type, e.g.:

    MyClass[] mcArray = gson.fromJson(jsonString, MyClass[].class);
    

    This way you avoid all the hassle with the Type object, and if you really need a list you can always convert the array to a list by:

    List<MyClass> mcList = Arrays.asList(mcArray);
    

    IMHO this is much more readable.

    And to make it be an actual list (that can be modified, see limitations of Arrays.asList()) then just do the following:

    List<MyClass> mcList = new ArrayList<>(Arrays.asList(mcArray));
    
    0 讨论(0)
提交回复
热议问题