问题
I have a JSON response from Facebook with the following structure:
{
"data": [
{
"id": "105458566194298_411506355589516",
"message": "...",
"type": "status",
"created_time": "2012-11-25T17:26:41+0000",
"updated_time": "2012-11-25T17:26:41+0000",
"comments": {
"count": 0
},
{
"id": "105458566194298_411506355589516",
"message": "...",
"type": "status",
"created_time": "2012-11-25T17:26:41+0000",
"updated_time": "2012-11-25T17:26:41+0000",
"comments": {
"count": 0
}
]
}
I'm trying to deserialize it using the Gson library:
public class FacebookPost {
public String Message;
public String Created_time;
}
Gson gson = new GsonBuilder().create();
Type listType = new TypeToken<ArrayList<FacebookPost>>() {}.getType();
ArrayList<FacebookPost> userList = gson.fromJson(responseJsonString, listType);
This would obviosuly just work if the response wasn't wrapper in the "data": [ ] - container. But how do I tell gson to look inside data in the JSON response?
回答1:
You should do something like that:
InputStream source = retrieveStream(url);
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
APIResponse response = gson.fromJson(reader, APIResponse.class);
With:
Public class APIResponse{
ArrayList <FacebookPost> data;
public class FacebookPost {
public String message;
public String created_time;
}
}
来源:https://stackoverflow.com/questions/13553584/deserialize-json-facebook-feed-using-gson