首页 > 解决方案 > 让 Jackson 序列化程序覆盖特定的忽略字段

问题描述

我有杰克逊这样的注释类:

public class MyClass {
   String field1;

   @JsonIgnore
   String field2;

   String field3;

   @JsonIgnore
   String field4;
}

假设我无法更改 MyClass 代码。那么,如何让 ObjectMapper 仅覆盖 field2 的 JsonIgnore 并将其序列化为 json ?我希望它忽略 field4。这是简单的几行代码吗?

我的常规序列化代码:

public String toJson(SomeObject obj){
    ObjectWriter ow = new ObjectMapper().writer().withDefaultPrettyPrinter();
    String json = null;
    try {
        json = ow.writeValueAsString(obj);
    } catch (JsonProcessingException e) {
        e.printStackTrace();
    }
    return json;
}

标签: javajsonjackson

解决方案


您可以使用MixIn功能:

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;

public class JsonApp {

    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        mapper.enable(SerializationFeature.INDENT_OUTPUT);
        mapper.addMixIn(MyClass.class, MyClassMixIn.class);

        System.out.println(mapper.writeValueAsString(new MyClass()));
    }
}

interface MyClassMixIn {

    @JsonProperty
    String getField2();
}

上面的代码打印:

{
  "field1" : "F1",
  "field2" : "F2",
  "field3" : "F3"
}

推荐阅读