作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有这门课:
public class DbReturned<T> {
public boolean State;
public int UserID;
public String Error;
public T row;
public List<T> Data;
public boolean Hr;
public boolean Credits;
}
信用等级是:
public class Credits {
public int id;
public int year;
public int month;
public double t1;
public double t2;
public double t3;
}
JSON 是
result = {"State":true,"UserID":0,"Error":null,"Data":[{"id":1,"year":2017,"month":1,"t1":77,"t2":88,"t3":99,"CreateBy":1,"CreateDate":"2017-08-22T13:58:27.497","ModifyBy":1,"ModifyDate":"2017-08-22T13:58:27.497"}],"row":null,"Credits":false,"Hr":false}
如何反序列化为 DbReturned:此代码无效:
Gson gson = new GsonBuilder().create();
if(result != null) {
DbReturned<Credits> data = gson.fromJson(result, DbReturned.class);
}
我用过:在 gradle 中编译 'com.google.code.gson:gson:2.4'
最佳答案
我找到了解决方案:
public <T> DbReturned<T> getResponse(final Class<T> dataClass ,
final String rawResponse)
{
return gson.fromJson(rawResponse,
getType(DbReturned.class,
dataClass));
}
private Type getType(final Class<?> rawClass,
final Class<?>
parameterClass)
{
return new ParameterizedType() {
@Override
public Type[] getActualTypeArguments() {
return new Type[]{parameterClass};
}
@Override
public Type getRawType() {
return rawClass;
}
@Override
public Type getOwnerType() {
return null;
}
};
}
我称它为:
DbReturned<Credits> data = getResponse(Credits.class ,
result.toString());
并且 Gson 变量在类的顶部是最终的:
public final Gson gson = new Gson();
关于android - 在 Android 的 GSON 中反序列化泛型类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46123762/
我是一名优秀的程序员,十分优秀!