使用GSON反序列化具有特定对象的通用容器

时间:2013-03-17 14:32:21

标签: java android gson

我有一个webservice,它为每个具有一些基本信息的请求返回相同的通用容器。例如,请求用户列表将给出以下响应:

{
   "error":false,
   "message":"Message goes here",
   "items":[
      {
         "id":1,
         "name":"Test User 1"
      },
      {
         "id":2,
         "name":"Test User 2"
      }
   ]
}

请求其他资源时,只有项目列表会有所不同:

{
   "error":false,
   "message":"Message goes here",
   "items":[
      {
         "id":3,
         "artist":"Artist 1",
         "year":2001
      },
      {
         "id":4,
         "artist":"Artist 2",
         "year":1980
      }
   ]
}

在我的客户端中,我想使用GSON映射java对象的响应:

public class ArtistRestResponse {
    private boolean error;
    private String message = "";
    private Artist[] items;     
}

但是,为了重构公共字段并阻止我为每个资源创建类,创建一般类型的RestResponse<T>类将是一个合乎逻辑的步骤:

public class RestResponse<T> {
   private boolean error;
   private String message = "";
   private T[] items;           
}

问题在于无法使用RestResponse<Artist> = new Gson().fromJson(json, RestResponse<Artist>.class);。 有没有办法使用这样的结构,还是有更好的方法来处理服务器响应?

1 个答案:

答案 0 :(得分:2)

您应该在这里使用TypeToken

final TypeToken<RestResponse<Artist>> token = new TypeToken<RestResponse<Artist>>() {};
final Type type = token.getType();
final Gson gson = new Gson();

final RestResponse<Artist> response = gson.fromJson(json, type);