我打算编写一个通用方法将 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
第二种情况?