gpt4 book ai didi

android - 在 Android 的 GSON 中反序列化泛型类

转载 作者:行者123 更新时间:2023-11-30 00:21:58 28 4
gpt4 key购买 nike

我有这门课:

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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com