【问题标题】:converting json string with Gson for generic model使用 Gson 将 json 字符串转换为通用模型
【发布时间】:2019-01-20 05:57:38
【问题描述】:

我有这样的课

public class Response<T>{
   T item;
   List<T>;
}

那么如何将这种模式中的 String 反序列化为一个带有gson.fromJson(targetString,...) 的泛型类?

我很高兴在改造库中使用 Response 在所需接口中返回参数

【问题讨论】:

    标签: android json gson retrofit2


    【解决方案1】:

    将列表转换为 gson

    public <T> String setList(List<T> list) {
        Gson gson = new Gson();
        return gson.toJson(list);  
    }
    

    将 gson 转换为列表

    public List<(desired class)> getList(){
        Gson gson = new Gson();
        String json = (pass json string);
        Type type = new TypeToken<List<(desired class)>>() {}.getType();
        return gson.fromJson(json, type);
    }
    

    将 gson 依赖添加到应用程序的 gradle 文件中。

    implementation 'com.google.code.gson:gson:2.8.6'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-16
      • 1970-01-01
      • 2017-08-11
      • 1970-01-01
      • 2013-05-19
      • 1970-01-01
      • 1970-01-01
      • 2017-01-24
      相关资源
      最近更新 更多