场景一:JSON目前虽然支持根据json串和Class来实现类型转换,如下所示:
User t = JSON.parseObject(json, User.class);
场景二:但目前却不支持:
User t = (User)JSON.parseObject(json);
主要是在泛型的框架类产品中,因泛型对象的class获取不方便(可以获取到当前泛型的class,只是感觉设计不好),所以希望提供一个不需要class就可以实现json串转为Bean对象。如下Demo运行时类型转换失败哈:
public class TypeReferenceTest < T > {
public T parse(Map<String, String> map) {
return JSON.parseObject(JSON.toJSONString(map), new TypeReference<T>() {});
}
public static void main(String[] args) {
Map<String, String> map = new HashMap<>();
map.put("teacherName", "zhangsan");
map.put("teacherAge", "23");
TypeReferenceTest<Teacher> typeReference = new TypeReferenceTest<Teacher>();
Teacher teacher = typeReference.parse(map);
System.out.println(teacher);
}
@Data
public static class Teacher {
private String teacherName;
private Integer teacherAge;
}
}
1条答案
按热度按时间eivgtgni1#
不是不想,而是做不到