TypeReference
fastjson-1.2.15.jar源码
注意上面这个案例.
/**
* String jsonStr = "[{\"id\":1001,\"name\":\"Jobs\"}]";
List<Model> models = JSON.parseObject(jsonStr, new TypeReference<List<Model>>() {});
*/
public static <T> T parseObject(String text, TypeReference<T> type, Feature... features) {
return (T) parseObject(text, type.type, ParserConfig.global, DEFAULT_PARSER_FEATURE, features);
}
单元测试上面的案例
原因在注掉的那一行.使用JSON.parseObject(jsonStr, Model.class)是转简单的类型,而使用JSON.parseObject(jsonStr, new TypeReference<List<Model>>() {})可以转复杂的类型。
@Test
public void contextLoads() {
String jsonStr = "[{\"id\":1001,\"name\":\"Jobs\"}]";
List<Model> models = JSON.parseObject(jsonStr, new TypeReference<List<Model>>() {});
// List<Model> models = JSON.parseObject(jsonStr, Model.class);这里就是用TypeReference的原因
System.out.println(models);
}
@ToString
@Data
private static class Model{
private String id;
private String name;
}