Jackson学习笔记

老版本的Jackson使用的包名为org.codehaus.jackson,而新版本使用的是com.fasterxml.jackson

Jackson主要包含了3个模块:

  • jackson-core
  • jackson-annotations
  • jackson-databind
    其中,jackson-annotations依赖于jackson-core,jackson-databind又依赖于jackson-annotations。

Jackson有三种方式处理Json:

  1. 使用底层的基于Stream的方式对Json的每一个小的组成部分进行控制
  2. 使用Tree Model,通过JsonNode处理单个Json节点
  3. 使用databind模块,直接对Java对象进行序列化和反序列化

通常来说,我们在日常开发中使用的是第3种方式,有时为了简便也会使用第2种方式,比如你要从一个很大的Json对象中只读取那么一两个字段的时候,采用databind方式显得有些重,JsonNode反而更简单。

使用ObjectMapper

本文的例子以jackson-databind-2.9.4为例。
创建Person类如下:

public class Person {
    private String name;
    private String address;
    private String mobile;


    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getMobile() {
        return mobile;
    }

    public void setMobile(String mobile) {
        this.mobile = mobile;
    }
}

序列化一个Person对象:

   public static void main(String[] args) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        Person person = new Person();
        person.setName("davenkin");
        person.setAddress("");
        System.out.println(objectMapper.writeValueAsString(person));
    }

返回结果:

{"name":"davenkin","address":"","mobile":null}

在默认情况下,ObjectMapper在序列化时,将所有的字段一一序列化,无论这些字段是否有值,或者为null。

另外,序列化依赖于getter方法,如果某个字段没有getter方法,那么该字段是不会被序列化的。由此可见,在序列化时,OjbectMapper是通过反射机制找到了对应的getter,然后将getter方法对应的字段序列化到Json中。请注意,此时ObjectMapper并不真正地检查getter对应的属性是否存在于Person对象上,而是通过getter的命名规约进行调用,比如对于getAbc()方法:

 public String getAbc(){
       return "this is abc";
   }

即便Person上没有abc属性,abc也会被序列化:

{"name":"davenkin","address":"","mobile":null,"abc":"this is abc"}

反序列化一个Json字符串,其中少了一个mobile字段:

public static void main(String[] args) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        Person person = objectMapper.readValue("{"name":"davenkin","address":""}", Person.class);

        System.out.println("name: " + person.getName());
        System.out.println("address: " + person.getAddress());
        System.out.println("mobile: " + person.getMobile());
    }

输出:

name: davenkin
address: 
mobile: null

可以看出,少了mobile字段,程序依然正常工作,只是mobile的值为null。

另外,如果我们向Json中增加一个Person中没有的字段:

  public static void main(String[] args) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        Person person = objectMapper.readValue("{"name":"davenkin","address":"","mobile":null,"extra":"extra-value"}", Person.class);

        System.out.println("name: " + person.getName());
        System.out.println("address: " + person.getAddress());
        System.out.println("mobile: " + person.getMobile());
    }

此时运行程序将报错:

Exception in thread "main" com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: 
Unrecognized field "extra" (class com.shell.b2b.factory.model.Person), not marked as ignorable (3 known properties: "mobile", "name", "address"])

表示在Person对象上找不到对应的extra属性,但是如果我们在Person上增加一个空的setter:

    public void setExtra(String extra) {
    }

那么此时运行成功,由此可见OjbectMapper是通过反射的机制,通过调用Json中字段所对应的setter方法进行反序列化的。并且此时,依赖于Person上有默认构造函数。

综上,在默认情况下(即不对ObjectMapper做任何额外配置,也不对Java对象加任何Annotation),ObjectMapper依赖于Java对象的默认的无参构造函数进行反序列化,并且严格地通过getter和setter的命名规约进行序列化和反序列化。

去除getter和setter

纯粹地为了技术方面的原因而添加getter和setter是不好的,可以通过以下方式去除掉对getter和setter的依赖:

objectMapper.setVisibility(ALL, NONE)
                .setVisibility(FIELD, ANY);

ObjectMapper将通过反射机制直接操作Java对象上的字段。

此时创建Person如下:

public class Person {
    private String name;
    private String address;
    private String mobile;

    public Person(String name, String address, String mobile) {
        this.name = name;
        this.address = address;
        this.mobile = mobile;
    }

}

序列化Person:

public static void main(String[] args) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(ALL, NONE)
                .setVisibility(FIELD, ANY);
        Person person = new Person("name", "address", "mobile");
        System.out.println(objectMapper.writeValueAsString(person));

    }

然而,此时反序列化的时候报错:

Exception in thread "main" com.fasterxml.jackson.databind.exc.InvalidDefinitionException: Cannot construct instance of `com.shell.b2b.factory.model.Person` (no Creators, like default construct, exist): cannot deserialize from Object value (no delegate- or property-based Creator)

这是因为ObjectMapper在为字段设值之前,无法初始化Person对象,此时有两种解决方式:

  1. 为Person增加默认构造函数:
private Person() {
    }

请注意,此时请将该构造函数设置为private的,因为我们不想因为纯技术原因而向外暴露一个会将Person类置于非法状态的构造函数(一个没有名字的Person还有什么用?)。

  1. 在已有构造函数上加上@JsonCreator注解,通常与@JsonProperty一起使用:
    @JsonCreator
    public Person(@JsonProperty("name") String name,
                  @JsonProperty("address") String address,
                  @JsonProperty("mobile") String mobile) {
        this.name = name;
        this.address = address;
        this.mobile = mobile;
    }

忽略字段

@JsonIgnore用于字段上,表示该字段在序列化和反序列化的时候都将被忽略。

@JsonIgnoreProperties主要用于类上:

@JsonIgnoreProperties(value = {"mobile","name"},ignoreUnknown = true)

表示对于mobile和name字段,反序列化和序列化均忽略,而对于Json中存在的未知字段,在反序列化时忽略,ignoreUnknown不对序列化起效。

序列化时排除null或者空字符串

@JsonInclude(JsonInclude.Include.NON_NULL)
public class Person {

表示在序列化Person时,将值为null的字段排除掉。

@JsonInclude(JsonInclude.Include.NON_EMPTY)
public class Person {

表示在序列化Person时,将值为null的字段或者空的字符串字段排除掉。

用某个方法的返回值序列化整个对象

有时我们并不想讲对象的所有字段都序列化,而是希望用一个方法的返回值来序列化,比如toString()方法,此时可以用@JsonValue

@JsonValue
public String toString(){
return "someValue";
}

此时整个对象在序列化后的值将变为“someValue”,需要注意的是,这种方式下,在反序列化时也需要有响应的机制。

Java 8 Data/Time API支持

Java 8中引入了全新的时间处理API,比如在多数情况下我们将使用Instant来表示某个事件发生的时间,Instant取代了之前的Timestamp。

但是,如果我们直接使用ObjectMapper来序列化Instant:

public static void main(String[] args) throws IOException {
        ObjectMapper objectMapper = new ObjectMapper();
        System.out.println(objectMapper.writeValueAsString(Instant.now()));

    }

将得到:

{"epochSecond":1520621382,"nano":959000000}

一个Instant需要两个字段来表示,同样的情况也出现在LocalDateTime上,即一个时间需要多个字段表示。

为了克服这种情况,可以引入Jackson的DataType模块:

    compile('com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.9.4')

然后配置ObjectMapper:

objectMapper.findAndRegisterModules();

此时,Instant将会被序列化为:

1520621578.637000000

如果你觉得这个数字不表意,那么可以:

objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

此时,Instant被序列化为:

"2018-03-09T18:53:48.214Z"

但这是一个UTC时区的时间,因此还不如直接使用数字呢。如果实在不喜欢数字,那么可以设置ObjectMapper的时区:

objectMapper.setTimeZone(getTimeZone(of("Asia/Shanghai")));

奇怪的是,这里必须显式地在ObjectMapper上设置,修改系统的默认时区对此时不生效的:

TimeZone.setDefault(getTimeZone(of("Asia/Shanghai")));

使用Jackson的推荐配置

  1. 对于所有的使用ObjectMapper的地方,推荐采用直接处理字段的方式,即:
objectMapper.setVisibility(ALL, NONE)
.setVisibility(FIELD, ANY);

另外,推荐加入Datatype模块。

在任何时候不要使用@JsonInclude(JsonInclude.Include.NON_EMPTY)@JsonInclude(JsonInclude.Include.NON_NULL)

  1. 对于接收客户端传来的请求(比如使用Spring MVC的Controller),使用@JsonCreator,并限制必须存在的字段为(require = true):
  @JsonCreator
    public Person(@JsonProperty(value = "name", required = true) String name,
                  @JsonProperty(value = "address", required = true) String address,
                  @JsonProperty(value = "mobile", required = true) String mobile) {
        this.name = name;
        this.address = address;
        this.mobile = mobile;
    }
  1. 如果要调用第三方的API,可以使用通过@JsonIgnoreProperties(ignoreUnknown = true)忽略掉所有不需要的字段。

  2. 如果要将Java对象持久化为Json格式,即对于采用NoSQL的系统而言,数据格式(schema)都被隐藏在了代码模型(Java的类)中,此时需要注意以下几点:

  • 在序列化时,不要使用@JsonInclude(JsonInclude.Include.NON_NULL)或者`@JsonInclude(JsonInclude.Include.NON_EMPTY),因为这样所产生的Json不能完整地反应数据schema。也即,在任何时候,代码模型中的所有字段都必须序列化到数据库中,包含了null值,空字符串等。

  • 由于软件在开发过程中经常会有数据库迁移,因此为了保证迁移之后的数据满足schema,我们需要保证迁移之后的数据字段和代码模型中的字段是严格一一对应的,不能多,也不能少,因此建议使用私有(表示只为技术而存在)的@JsonCreator构造函数和@JsonProperty(value = "name", required = true)来反序列化对象。



作者:无知者云
链接:https://www.jianshu.com/p/4bd355715419
來源:简书
简书著作权归作者所有,任何形式的转载都请联系作者获得授权并注明出处。
原文地址:https://www.cnblogs.com/mywangpingan/p/10031282.html