Deserialize JSON Facebook feed using Gson

China☆狼群 提交于 2019-12-11 06:27:13

问题


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

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