Google Gson - deserialize list object? (generic type)

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

    I want to add for one more possibility. If you don't want to use TypeToken and want to convert json objects array to an ArrayList, then you can proceed like this:

    If your json structure is like:

    {
    
    "results": [
        {
            "a": 100,
            "b": "value1",
            "c": true
        },
        {
            "a": 200,
            "b": "value2",
            "c": false
        },
        {
            "a": 300,
            "b": "value3",
            "c": true
        }
    ]
    

    }

    and your class structure is like:

    public class ClassName implements Parcelable {
    
        public ArrayList results = new ArrayList();
        public static class InnerClassName {
            int a;
            String b;
            boolean c;      
        }
    }
    

    then you can parse it like:

    Gson gson = new Gson();
    final ClassName className = gson.fromJson(data, ClassName.class);
    int currentTotal = className.results.size();
    

    Now you can access each element of className object.

提交回复
热议问题