java - 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
第二种情况?
解决方案
类型擦除意味着T
在运行时丢失,所以
new TypeToken<List<T>>() {}.getType()
变成
new TypeToken<List>() {}.getType()
这意味着 Gson 不知道列表元素类型 ( City
)。
由于它不知道将列表中的 JSON 对象解析为对象,因此City
将它们解析为Map<String, Object>
对象,因此错误消息“Map
无法强制转换为City
”。
使用的注释代码TypeToken.getParameterized()
将起作用,所以坚持下去。
推荐阅读
- abap - 模态对话框以全屏显示而不是对话框
- apache-beam - Apache Beam 中的模式是什么?
- python - 以视觉可读的方式将张量写入文件
- react-native - Realm V10,如何在 React Native 中持久化身份验证
- javascript - 无法使用 express.static (Node JS) 获取图像 EJS
- mqtt - MQTT Sensor 提供的数据过多
- enterprise-architect - 用于 SysML 的 Sparx EA - 预计对 BDD 的更改也会影响 IBD
- r - 如何在以数字命名的数据框中使用for循环
- linux - Rails 6 部署到 Digital Ocean Ubuntu v20 cap 生产部署挂起捆绑安装
- java - 比较看起来相同但不同的本地化字符串的更好方法是什么