I would like to define my custom serialization strategy (which fields to include), while using Jackson. I know, that I can do it with views/filters, but it introduces very bad thing - using string-representation of field names, which automatically enables problems with auto-refactoring.
How do I force Jackson into serializing only annotated properties and nothing more?
If there are fields in Java objects that do not wish to be serialized, we can use the @JsonIgnore annotation in the Jackson library. The @JsonIgnore can be used at the field level, for ignoring fields during the serialization and deserialization.
Ignore All Fields by Type Finally, we can ignore all fields of a specified type, using the @JsonIgnoreType annotation. If we control the type, then we can annotate the class directly: @JsonIgnoreType public class SomeType { ... } More often than not, however, we don't have control of the class itself.
ObjectMapper; ObjectMapper objectMapper = new ObjectMapper(); objectMapper. configure(DeserializationFeature. FAIL_ON_UNKNOWN_PROPERTIES, false); This will now ignore unknown properties for any JSON it's going to parse, You should only use this option if you can't annotate a class with @JsonIgnoreProperties annotation.
If you disable all auto-detection it should only serialize the properties that you have annotated--whether it be the properties themselves or the getters. Here's a simple example:
private ObjectMapper om;
@Before
public void setUp() throws Exception {
om = new ObjectMapper();
// disable auto detection
om.disable(MapperFeature.AUTO_DETECT_CREATORS,
MapperFeature.AUTO_DETECT_FIELDS,
MapperFeature.AUTO_DETECT_GETTERS,
MapperFeature.AUTO_DETECT_IS_GETTERS);
// if you want to prevent an exception when classes have no annotated properties
om.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
}
@Test
public void test() throws Exception {
BlahClass blahClass = new BlahClass(5, "email", true);
String s = om.writeValueAsString(blahClass);
System.out.println(s);
}
public static class BlahClass {
@JsonProperty("id")
public Integer id;
@JsonProperty("email")
public String email;
public boolean isThing;
public BlahClass(Integer id, String email, boolean thing) {
this.id = id;
this.email = email;
isThing = thing;
}
}
In case you want to do this without configuring the mapper just for a specific type:
@JsonAutoDetect(
fieldVisibility = Visibility.NONE,
setterVisibility = Visibility.NONE,
getterVisibility = Visibility.NONE,
isGetterVisibility = Visibility.NONE,
creatorVisibility = Visibility.NONE
)
public class BlahClass {
@JsonProperty("id")
private Integer id;
@JsonProperty("email")
private String email;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With