前言
ackson是一个开源的Java序列化和反序列化工具,可以将Java对象序列化为XML或JSON格式的字符串,以及将XML或JSON格式的字符串反序列化为Java对象。
依赖
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.9</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.7.9</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.7.9</version>
</dependency>
JACKSON序列化与反序列化
Jackson提供了ObjectMapper.writeValueAsString()和ObjectMapper.readValue()两个方法来实现序列化和反序列化的功能,不难看出 write就是序列化,而read 就是反序列化。
demo
package JACKSON;
public class User {
private String username;
private String password;
public User() {
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
public String getUsername() {
return username;
}
public String getPassword() {
return password;
}
public void setUsername(String username) {
this.username = username;
}
public void setPassword(String password) {
this.password = password;
}
}
测试:
package JACKSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
public class JacksonTest {
public static void main(String[] args) throws IOException {
User user = new User("snowy","123456");
ObjectMapper mapper = new ObjectMapper();
String json = mapper.writeValueAsString(user);
System.out.println(json);
User other = mapper.readValue(json,User.class);
System.out.println(other);
}
}
运行结果
感觉和fastjson 差不多,需要解决多态的问题,在fastjson中引入的是@type解决该问题
Jackson中也有与之对应的方法,Jackson实现了JacksonPolymorphicDeserialization机制来解决这个问题,有两种方法:DefaultTyping和@JsonTypeInfo注解。
DefaultTyping
Jackson提供一个enableDefaultTyping设置,其包含4个值,查看com.fasterxml.jackson.databind.ObjectMapper.DefaultTyping可看到相关介绍信息:
默认情况下 DefaultTyping是第二个设置,也就是 OBJECT_AND_NON_CONCRETE