Android gson deserialization into list

筅森魡賤 提交于 2019-12-11 02:42:56

问题


I am trying to parse a json string into a list, or arraylist. I have the following json response coming from a WCF RESTful service I created for an Android project

[
    {
        "Class": "Lorem",
        "Company": "Ipsum",
        "Id": "XXXX",
        "Name": "Avent"
    },
    {
        "Class": "Consectetur",
        "Company": "Adipiscing",
        "Id": "YYYYY",
        "Name": "Nulla"
    }
]

I've read several examples of parsing gson results on here, but I'm having difficulty enacting a container class as I've seen. I've gotten it to read a single result into a Group class, but cannot get it to parse into any kind of List or ArrayList.

Group Class:

public class Group {

    private String Id;
    private String Name;
    private String Class;
    private String Company;   
}

Group Container Class:

public class Groups {
    private List<Group> GRP;
}

gson parsing statement:

Groups GRP = gson.fromJson(jsonString, Groups.class);

I did have to do some manipulation of the jsonString because it was showing up with some spaces in the string (after the commas), and it started working after I removed them, at least for parsing into a single element. Not sure if that effects anything, but figured I'd mention it.

Also, I tried do the

Type listType = new TypeToken>() {}.getType(); gson.toJson(myStrings, listType);

but that doesn't seem to work either, and I didn't know if that is necessary for my situation.


回答1:


List<Group> groups = gson.fromJson(jsonString, new TypeToken<List<Group>>() {}.getType())


来源:https://stackoverflow.com/questions/7959157/android-gson-deserialization-into-list

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!