使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;
}
h975969910 回答:使Jackson序列化程序覆盖特定的忽略字段

您可以使用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"
}
,

您可以像这样使用自定义序列化程序(我将重构交给您):

private String getJson(final MyClass obj) {
    final ObjectMapper om = new ObjectMapper();
    om.registerModule(new SimpleModule(
            "CustomModule",Version.unknownVersion(),Collections.emptyMap(),Collections.singletonList(new StdSerializer<MyClass>(MyClass.class) {

                @Override
                public void serialize(final MyClass value,final JsonGenerator jgen,final SerializerProvider provider) throws IOException {
                    jgen.writeStartObject();
                    jgen.writeStringField("field1",value.field1);
                    jgen.writeStringField("field2",value.field2);
                    jgen.writeStringField("field3",value.field3);
                    jgen.writeEndObject();
                }

            })));

    try {
        return om.writeValueAsString(obj);
    } catch (final JsonProcessingException e) {
        throw new RuntimeException(e);
    }
}

您可以在google / stackoverflow上找到有关自定义序列化程序的更多信息,我想我回答了类似的问题here

本文链接:https://www.f2er.com/3139218.html

大家都在问