JSON在开发过程中的作用越来越重要,特别是异构平台之间,使用JSON来通信是非常简单的。一般情况下,在使用json进行转换的时候,一般会采用JSONObject或者是google的Gson。今天给大家介绍两个非常好用,功能非常强大的工具:fastjson和jackson。
两个的依赖如下:
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.1.37</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
两者的使用方法都非常的简单:
fastjson:
json转Object--->JSON.parseObject(json,clazz);
Object转json--->JSON.toJSONString(obj);
jackson:
json转Object--->new ObjectMapper().readValue(json,clazz);
Object转json--->new ObjectMapper().writeValueAsString(obj);
对于泛型的转换如下:
String str = "[{\"age\":13,\"name\":\"zhangsan\"}]";
//fastjson
List<User> l = JSON.parseObject(str,new TypeReference<List<User>>(){});
System.out.println(l.get(0).getName());
//jackson
ObjectMapper mapper = new ObjectMapper();
JavaType type = mapper.getTypeFactory().constructParametricType(List.class, User.class);
List<User> ll = mapper.readValue(str, type);
System.out.println(ll.get(0).getName());
前段时间报出的fastjson的漏洞,相信大家都已经修复了。最近在看的时候,发现这么一个说明:
https://github.com/alibaba/fastjson/wiki/enable_autotype
于是,好奇这个问题是怎么引出的。怎么判断是否使用了autotype呢?
示例代码如下:
ParserConfig.getGlobalInstance().addAccept("com.test.model.");
String str = "{\"@type\":\"com.test.model.Config\", \"test\":\"test\",\"name\":\"hello\"}";
Config c = (Config) JSON.parse(str);
System.out.println(JSON.toJSONString(c));
升级1.2.28之后,只需要加上ParserConfig的配置即可解决。