解析带泛型的json数据

ublic class Test {
    public static void main(String[] args) {
        Map map = new HashMap<>();
        User user = new User();
        user.setAge(11);
        user.setId(11);
        map.put("1",user);
        String jsonString = JSON.toJSONString(map);
        String str = new String(jsonString.getBytes());

        /**
         * fastjson
         */
        Map map1 = JSON.parseObject(jsonString, Map.class);
        System.out.println("FastJson直接解析:"+ map1.get("1") );
        Map map2 = JSON.parseObject(str, new TypeReference>(){}.getType());
        System.out.println("FastJson包装解析:" + map2.get("1"));

        /**
         * gson
         */
        Gson gson = new Gson();
        Map map3 = gson.fromJson(str, Map.class);
        System.out.println("gson直接解析:"+ map3.get("1"));
        Map map4 = gson.fromJson(str, new TypeToken>(){}.getType());
        System.out.println("gson包装解析:"+ map4.get("1"));

        //直接解析的没法转换成对象
        User user3 = map1.get("1");
        System.out.println(user3);

        User user1 = map4.get("1");
        System.out.println(user1);
        User user2 = map3.get("1");
        System.out.println(user2);


    }
}

执行结果

FastJson直接解析:{"id":11,"age":11}
FastJson包装解析:User{id=11, name='null', age=11}
gson直接解析:{age=11.0, id=11.0}
gson包装解析:User{id=11, name='null', age=11}
Exception in thread "main" java.lang.ClassCastException: com.google.gson.internal.LinkedTreeMap cannot be cast to com.cyy.entity.User
User{id=11, name='null', age=11}
	at com.cyy.serialize.Test.main(Test.java:45)

直接解析的并没有转换成对象, 所以后面从map里拿取对象的时候 会报转换异常

你可能感兴趣的:(解析带泛型的json数据)