【发布时间】:2014-10-26 12:19:04
【问题描述】:
请帮忙T_T挖了2天来解决这个问题!
我正在使用 Retrofit 在我的应用程序中执行一些网络任务, 我调用的其中一个 API 有时会返回不同的对象,但我知道每次调用它的时间和返回内容。
在这种情况下,Message 是一个对象
{
"key": "some key",
"category": "some category",
"channel": "some channel",
"status": "some status",
"message": {
"someValue": "54",
"someOtherValue": "5353"
}
}
这里Message 是一个字符串
{
"key": "some key",
"category": "some category",
"channel": "some channel",
"status": "some status",
"message": "this is a string"
}
所以我试图通过使用泛型来实现这个解决方案的良好设计, 我有一个像这样的通用类,
ContentResponse 类
public class ContentResponse<T> {
private List<Content<T>> content = new ArrayList<Content<T>>();
//getters and setters
}
内容类
public class Content<T>
{
private String key;
private String category;
private String channel;
private String status;
private T message;
//getters and setters
}
ContentInterface 类
public interface ContentInterface<T>
{
@GET("/public/content/{category}")
ContentResponse<T> getContent(@Path(PathParameters.CATEGORY) String category);
}
问题出在这里
public class ContentRequest<T> extends RetrofitSpiceRequest<ContentResponse<T>, ContentInterface<T>>
{
String category;
public ContentRequest(Class<ContentResponse<T>> clazz, Class<ContentInterface<T>> retrofittedInterfaceClass, String category) {
super(clazz, retrofittedInterfaceClass);
this.category = category;
}
@Override
public ContentResponse<T> loadDataFromNetwork() throws Exception {
return getService().getContent(category);
}
}
在这种情况下,我知道返回的对象是 Map<String, String>
contentRequest = new ContentRequest(new Class<ContentResponse<Map<String, String>>>(),
new Class<ContentInterface<Map<String, String>>>(),
"appstrings");
但我明白了!!
'class()' 在 java.lang.Class 中不公开
我不能只打电话给ContentResponse<Map<String,String>>.class,我可以在这里做什么?
【问题讨论】:
标签: java android json generics retrofit