首页 > 解决方案 > Gson 去串化列表和类,这里的擦除是如何工作的?

问题描述

我打算编写一个通用方法将 json 列表转换为带有类的特定列表。这是通用的 json 解析器:

public class JsonParserUtils {

    private static Gson gson = new Gson();

    public static <T> String toJson(T object) {
        if (object == null) {
            return null;
        }
        return gson.toJson(object);
    }

    public static <T> T fromJson(String json, Class<T> className) {
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        T object = gson.fromJson(json, className);
        return object;
    }

    public static <T> List<T> fromJsonList(String jsonList, Class<T> className) {
        // return gson.fromJson(jsonList, TypeToken.getParameterized(List.class, className).getType());
        return gson.fromJson(jsonList, new TypeToken<List<T>>() {}.getType());
    }

}

这是一个我想转换为 Json 并返回到 Pojo 的虚拟类。

public class City {

    private String city;

    public City(String city) {
        this.city = city;
    }

    @Override
    public String toString() {
        return "City [city=" + city + "]";
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

}

这是一个简单的测试,看看它是否有效:

public class TestParser {

    public static void main(String[] args) {
        City city = new City("test");
        String cityJson = JsonParserUtils.toJson(city);
        System.out.println(cityJson);

        City fromJson = JsonParserUtils.fromJson(cityJson, City.class);
        System.out.println(fromJson.getCity());  // Why does this work?

        List<City> list = new LinkedList<>();
        list.add(city);
        String cityListJson = JsonParserUtils.toJson(list);
        System.out.println(cityListJson);

        List<City> fromJsonList = JsonParserUtils.fromJsonList(cityListJson, City.class);
        System.out.println(fromJsonList.get(0).getCity()); // Why does this not work?


    }

}

控制台输出如下:

{"city":"test"}
test
[{"city":"test"}]
Exception in thread "main" java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to com.jtraq.hospital.vos.City
    at com.jtraq.hospital.vos.TestParser.main(TestParser.java:24)

我正在努力理解为什么fromJson(json, class)有效但fromJsonList(json, class)无效。如果擦除适用,那么它是否适用于两种情况?为什么第一种方法确定类是类型City而不是LinkedHashMap第二种情况?

标签: javajsongenericsgsonerasure

解决方案


类型擦除意味着T在运行时丢失,所以

new TypeToken<List<T>>() {}.getType()

变成

new TypeToken<List>() {}.getType()

这意味着 Gson 不知道列表元素类型 ( City)。

由于它不知道将列表中的 JSON 对象解析为对象,因此City将它们解析为Map<String, Object>对象,因此错误消息“Map无法强制转换为City”。

使用的注释代码TypeToken.getParameterized()将起作用,所以坚持下去。


推荐阅读