fastjson中遇到的坑

public static void main(String[] args) {
        Result<User> t = new Result<User>();
        String str = "{\"model\":{\"age\":20,\"name\":\"xyz\"},\"success\":false}";
        System.out.println(JSON.parseObject(str,t.getClass()).getModel().getClass());
        System.out.println(JSON.parseObject(str,new TypeReference<Result<User>>(){}).getModel().getClass());
    }
会出现下面的错误:
Exception in thread "main" java.lang.ClassCastException: com.alibaba.fastjson.JSONObject cannot be cast to User
class com.alibaba.fastjson.JSONObject
因为fastjson会缓存class的beaninfo信息
推荐统一使用泛型方式,使用TypeReference方式

猜你喜欢

转载自mutourenoo.iteye.com/blog/2304481