3

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.

Precious Roy
  • 1,086
  • 1
  • 9
  • 19

1 Answers1

5
List<Group> groups = gson.fromJson(jsonString, new TypeToken<List<Group>>() {}.getType())
user634545
  • 9,099
  • 5
  • 29
  • 40
  • I could have sworn I'd tried that way before. I guess I don't need a container class after all. Would it be best to build a list or an arraylist, seeing how I want to display one of the fields in a listview? I'm under the impression I have to put the field into an string[] to pass it to the listview adapter. – Precious Roy Nov 01 '11 at 13:12
  • I'm trying to figure out how to display the "Name" fields in a listview – Precious Roy Nov 01 '11 at 17:25