前言
我们常用的json解析工具包括:阿里的Fastjson、Jackson和google的Gson,据测试,Fastjson较Jackson快了20%左右,Gson最慢。所以很多程序猿喜欢使用Fastjson。但是阿里提供的Fastjson近期频繁爆出安全漏洞,同时本着最小依赖原则,建议使用Jackson替换Fastjson
需要的依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.5</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.5</version>
</dependency>
用法示例
- ObjectNode与ArrayNode
当我们需要操作一个json对象或者json数组的时候,我们可以使用下面的方法来构造ObjectNode和ArrayNode,类似fastjson中的JSONObject和JSONArray。
ObjectMapper mapper = new ObjectMapper();
ObjectNode node = mapper.createObjectNode();
node.put("name", "test");
node.put("age", 20);
System.out.println(node);
ArrayNode array = mapper.createArrayNode();
array.add(node);
System.out.println(array);
- json转对象
ObjectMapper objectMapper = new ObjectMapper();
Person person = objectMapper.readValue(jsonString, Person.class);
System.out.println(person.toString());
- 对象转json
ObjectMapper objectMapper = new ObjectMapper();
Person person = new Person().setName("test").setAge(20);
String jsonString = objectMapper.writeValueAsString(person);
System.out.println("JsonString: " + jsonString);
- json转泛型对象
ObjectMapper objectMapper = new ObjectMapper();
List<Person> personList = objectMapper.readValue(jsonString, new TypeReference<List<Person>>() {});
System.out.println(personList.toString());
网友评论