我有一个网络服务,它为每个请求返回相同的通用容器以及一些基本信息。例如,请求用户列表将给出以下响应:
{
"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;
}
但是,为了重构公共(public)字段并阻止我为每个资源创建类,创建通用类型 RestResponse<T>
将是一个合乎逻辑的步骤。类:
public class RestResponse<T> {
private boolean error;
private String message = "";
private T[] items;
}
问题是无法使用RestResponse<Artist> = new Gson().fromJson(json, RestResponse<Artist>.class);
。
有什么方法可以使用这样的构造,或者有更好的方法来处理服务器响应吗?
最佳答案
您应该在此处使用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);
关于java - 使用 GSON 反序列化通用容器与特定对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15461896/