android - 使用 Gson 反序列化数据时将 LinkedTreeMap 转换为 List
问题描述
我将从服务器传入的 json 存储到我的模型类中。我试图创建泛化响应类以在领域数据库中存储不同 Web 服务的响应。
这是我的回复课
public class TResponse<T> {
@Expose
private String code;
@Expose
private String message;
@Expose
private Summary summary;
@Expose
private String status;
@Expose
private String error;
@Expose
private List errors;
@Expose
private List<T> response;
}
我要存储的 Json
{
"diabetes": [
{
"_id": "5b83a79e4297c60021cc0ee2",
"blood_glucose": 137,
"timestamp": "2018-07-31T09:01:48+00:00",
"utc_offset": "+05:30",
"last_updated": "2018-08-27T07:26:22+00:00"
},
{
"_id": "5b83a79e4297c60021cc0e88",
"blood_glucose": 140,
"timestamp": "2018-07-31T09:01:48+00:00",
"utc_offset": "+05:30",
"last_updated": "2018-08-27T07:26:22+00:00"
}
],
"errors": [
{
"code": 409,
"message": "Conflict",
"errors": "Activity is already taken",
"activity_id": "468eb4bf-0d84-4b77-bb94-daebd0063955"
}
]
}
糖尿病数组将存储到通用列表中List<T> response
,现在为了将糖尿病映射到List<T> response
我必须在反序列化器中显式映射该列表,为此我正在使用Gson
解析器
@Override
public T deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
TResponse tResponse = new TResponse();
tResponse.setSummary(context.deserialize(json.getAsJsonObject().get("summary"),Summary.class));
tResponse.setResponse(context.deserialize(json.getAsJsonObject().get(mKey.toLowerCase()),List.class));
tResponse.setErrors(context.deserialize(json.getAsJsonObject().get("errors").getAsJsonArray(),List.class));
return (T) tResponse;
}
在上面的代码中 mKey 是Diabetes.class
现在的问题是,当我尝试创建一个新对象TResponse
并将数据存储到其中时,Gson 将其存储LinkedTreeMap
为List
看下面的截图
解决方案
我只需要处理参数化的类类型,在这里我只是传递原始类信息,因此解析器无法弄清楚列表下面的内容
tResponse.setResponse(context.deserialize(json.getAsJsonObject().get(mKey.toLowerCase()),getType(List.class,Diabetes.class)));
以下是处理参数类并返回适当的函数Type
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;
}
};
}
推荐阅读
- javascript - 同一个 Electron 窗口中的两个浏览器
- angular - Angular 7 引导模式在第二次单击时未打开
- spring - 有没有办法限制文件处理程序实例的数量?
- android - 在从 raw 文件夹的 videoview 中播放视频时,在开始播放视频之前出现黑屏
- python-2.7 - TemplateSyntaxError:第 25 行的块标记无效:'end',预期为 'endblock'。您是否忘记注册或加载此标签?
- windows - 将 Windows 10 触摸板手势传递到远程桌面
- angular - 角度 7 rxjs 升级失败的单元测试
- docker - 忽略 docker 卷映射中的某些目录
- excel - 如何更改宏功能
- sql - 使用唯一标识符将值从一个字段复制到另一个字段