首页 > 解决方案 > 使用 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 将其存储LinkedTreeMapList

看下面的截图

在此处输入图像描述

标签: androidrealmgson

解决方案


我只需要处理参数化的类类型,在这里我只是传递原始类信息,因此解析器无法弄清楚列表下面的内容

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;
            }

        };
    }

推荐阅读