How to deserialize a list using GSON or another JSON library in Java?

前端 未结 4 1196
半阙折子戏
半阙折子戏 2020-11-27 10:11

I can serialize a List in my servlet on GAE, but I can\'t deserialize it. What am I doing wrong?

This is my class Video in GAE, which is s

相关标签:
4条回答
  • 2020-11-27 10:43

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

    Video[] videoArray = gson.fromJson(json, Video[].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, e.g.:

    List<Video> videoList = Arrays.asList(videoArray);
    

    IMHO this is much more readable.


    In Kotlin this looks like this:

    Gson().fromJson(jsonString, Array<Video>::class.java)
    

    To convert this array into List, just use .toList() method

    0 讨论(0)
  • With Gson, you'd just need to do something like:

    List<Video> videos = gson.fromJson(json, new TypeToken<List<Video>>(){}.getType());
    

    You might also need to provide a no-arg constructor on the Video class you're deserializing to.

    0 讨论(0)
  • 2020-11-27 11:06

    I recomend this one-liner

    List<Video> videos = Arrays.asList(new Gson().fromJson(json, Video[].class));
    

    Warning: the list of videos, returned by Arrays.asList is immutable - you can't insert new values. If you need to modify it, wrap in new ArrayList<>(...).


    Reference:

    1. Method Arrays#asList
    2. Constructor Gson
    3. Method Gson#fromJson (source json may be of type JsonElement, Reader, or String)
    4. Interface List
    5. JLS - Arrays
    6. JLS - Generic Interfaces
    0 讨论(0)
  • 2020-11-27 11:06

    Be careful using the answer provide by @DevNG. Arrays.asList() returns internal implementation of ArrayList that doesn't implement some useful methods like add(), delete(), etc. If you call them an UnsupportedOperationException will be thrown. In order to get real ArrayList instance you need to write something like this:

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