欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

com.fasterxml.jackson---03_如何使用ObjectMapper序列化以及反序列化一个对象

程序员文章站 2024-02-04 13:44:58
...

本文的例子以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) {
    }

相关标签: com.fasterxml.jackson