1

I'm building a client server web application and stuck on this:

I'm getting an array of users "FriendsIDList:":

"data":{
    "name":"anna",
    "BirthDate":"2010-01-01",
    "FriendsIDList":{
        "email":"anna1@gmail.com",
        "email":"anna2@gmail.com"
    }
}}

Without the array I have no problem reading the data like this:

GsonBuilder gb = new GsonBuilder();
gb.setDateFormat("yyyy-MM-dd");
gson = gb.create();
newUser= gson.fromJson(data, user.class);

How can I read this array? I'm using LinkedList in my user class:

LinkedList FriendsIDList;
Programmer Bruce
  • 64,977
  • 7
  • 99
  • 97
Nusha
  • 262
  • 2
  • 12

2 Answers2

0

In case you have a single user that contains the FriendList then your last line will work as you have mentioned.

Try defining you FriendList property as follows:

LinkedList<Email> FriendList;

And create Email Class:

public class Email {
  private String email;
}
rizzz86
  • 3,862
  • 8
  • 35
  • 52
  • and when should I use this? Do I still need to use my last line? – Nusha May 31 '12 at 13:23
  • It means that you have to provide the type of data that is returned from json. If json is returning a list you have to create a Type for list and pass that in the fromJson method – rizzz86 May 31 '12 at 13:25
  • According to your last line you are expecting a single user object (user.class). But now you have changed your json structure and returning a list or users. So you need to replace the last line with my code – rizzz86 May 31 '12 at 13:26
  • @Nusha lets join the chat room to discuss this in detail – rizzz86 May 31 '12 at 14:00
  • I believe that the answer that you are seeking is in http://stackoverflow.com/questions/6223023/parsing-json-with-gson-object-sometimes-contains-list-sometimes-contains-object – rlinden May 31 '12 at 14:28
0

The JSON spec says this:

A name is a string. A single colon comes after each name, separating the name from the value. A single comma separates a value from a following name. The names within an object SHOULD be unique.

Unfortunately Gson doesn't natively support non-unique names in name/value pairs. So it cannot properly handle your 'email' properties:

{"email":"anna1@gmail.com","email":"anna2@gmail.com"}

You can work-around this by writing your own TypeAdapter. Your implementation should accumulate email strings into a list. You'll probably want to use a special wrapper object in your data model like EmailAddressList to make this easy.

static class FriendsIDList {
  List<String> emails;
}

static TypeAdapter<FriendsIDList> friendsIDListAdapter
        = new TypeAdapter<FriendsIDList>() {
    ... // code to read and write emails
}
Jesse Wilson
  • 39,078
  • 8
  • 121
  • 128