Make Jackson serializer override specific ignored fields

Eran Morad :

I have Jackson annotated class like this :

public class MyClass {
   String field1;

   @JsonIgnore
   String field2;

   String field3;

   @JsonIgnore
   String field4;
}

Assume that I cannot change MyClass code. Then, how can I make ObjectMapper override the JsonIgnore for field2 only and serialize it to json ? I want it to ignore field4 though. Is this easy and few lines of code ?

My code for regular serialization :

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;
}
Michał Ziober :

You can use MixIn feature:

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();
}

Above code prints:

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=323822&siteId=1