使用Gson反序列化JSON Facebook提要 [英] Deserialize JSON Facebook feed using Gson

查看:92
本文介绍了使用Gson反序列化JSON Facebook提要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个来自Facebook的JSON响应,其结构如下:

  {
data:[
{
id:105458566194298_411506355589516,
message:...,
type:status,
created_time: 2012-11-25T17:26:41 + 0000,
updated_time:2012-11-25T17:26:41 + 0000,
comments:{
计数:
},
{
id:105458566194298_411506355589516,
message:...,
type:状态,
created_time:2012-11-25T17:26:41 + 0000,
updated_time:2012-11-25T17:26:41 + 0000,
意见:{
count:0
}
]
}

我试图用Gson库反序列化它:

  public class FacebookPost {
public String Message;
public String Created_time;






  Gson gson = new GsonBuilder()。create(); 

类型listType = new TypeToken< ArrayList< FacebookPost>>(){} .getType();

ArrayList< FacebookPost> userList = gson.fromJson(responseJsonString,listType);

如果响应不是封装在中的数据:[] - 容器。但是,如何告诉gson在JSON响应中查看 data 内部?

您应该这样做:

  InputStream source = retrieveStream(url); 
Gson gson = new Gson();
Reader reader = new InputStreamReader(source);
APIResponse response = gson.fromJson(reader,APIResponse.class);

与:

 公共类APIResponse {

ArrayList< FacebookPost>数据;

public class FacebookPost {
public String message;
public String created_time;
}
}


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?

解决方案

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;
    }
}

这篇关于使用Gson反序列化JSON Facebook提要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆