I have a json string like this:
http://pastebin.com/ckUZadwL
I’m trying to use gson to parse them. However, I have a question. In new reponse, the user element contains generic id as the key, and since it’s in the inner class, I’m not sure how to parse it.
Thank you for your help.
Here are a few class containers I build to store there data:
public class CometCallback
{
public int new_offset;
public Data[] data;
}
public class Data
{
public long plurk_id;
public int response_count;
public Response response;
public UserInfo user;
public String type;
public Plurk plurk;
}
public class Response
{
public String lang;
public String content_raw;
public long user_id;
public String qualifier;
public long plurk_id;
public String content;
public long id;
public String posted;
}
public class Plurk extends Response
{
public Object[] replurkers;
public int responses_seen;
public int replurkers_count;
public String replurker_id;
public int response_count;
public boolean replurkable;
public Object limited_to;
public int favorite_count;
public int is_unread;
public Object[] favorers;
public int plurk_type;
public boolean replurked;
public boolean favorite;
public int no_comments;
public long owner_id;
}
I have several thing to share about you post:
The biggest problem you will face is that the user has very weird
json serialization – its id is used as key. The only way I can think of is to use enableComplexMapKeySerialization option of the
GsonBuilder. Then you will need to declareUsewrInfoas containing only one elementMap<Integer, User>and declare theUserbean with all the attributes mapped to the id.I suppose you know that with gson it is not required to have the
class field names matching the keys in the gson. E.g you can still
use a camel-cased newOffset and parse in it the field new_offset.
You just need to place the gson annotation
@SerializedName("new_offser")above the declaration of the field.Here is how you do the deserialization from json using gson. It is
really straight forward:
I will discuss on the option of
DateFormatin the next section.serializeNullsis needed, because I saw the attributes with nullvalues are also serialized like
"date_of_birth": null.About the
DateFormat– I saw you declarepublic String posted;as string. However gson can parse the dates straight out of the json
string for you as long as you specify the exact format the dates
will be in. Here is the exact format I think you define your dates
in:
Now declaring this and passing it in the
setDateFormat(MY_DATE_FORMAT)method you should be able to changeall your dates to be read as dates and gson will parse them for you.
By the way, I suppose you know it, but you can deserialize json
arrays to lists for example. This happens by just declaring the
fields accordingly and gson automagically will store in them.
Hopefully all this will help you deserialize your data. Happy coding!