How to Specify Jackson to Only Use Fields - Preferably Globally

How to specify jackson to only use fields - preferably globally

You can configure individual ObjectMappers like this:

ObjectMapper mapper  = new ObjectMapper();
mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker()
.withFieldVisibility(JsonAutoDetect.Visibility.ANY)
.withGetterVisibility(JsonAutoDetect.Visibility.NONE)
.withSetterVisibility(JsonAutoDetect.Visibility.NONE)
.withCreatorVisibility(JsonAutoDetect.Visibility.NONE));

If you want it set globally, I usually access a configured mapper through a wrapper class.

How to change Jackson to detect all fields in a POJO, other than only public ones?

Jackson does support reading values from private member fields, but does not do it by default.

You can configure the behavior globally in the Spring Boot config like

jackson:
visibility.field: any
visibility.getter: none
visibility.setter: none
visibility.is-getter: none

(this config will only look for member fields and no longer check get, set and is methods)

You could also use the @JsonAutoDetect annotation to do the same setting for a specific class.

How to specify jackson to only use fields - preferably globally

You can configure individual ObjectMappers like this:

ObjectMapper mapper  = new ObjectMapper();
mapper.setVisibility(mapper.getSerializationConfig().getDefaultVisibilityChecker()
.withFieldVisibility(JsonAutoDetect.Visibility.ANY)
.withGetterVisibility(JsonAutoDetect.Visibility.NONE)
.withSetterVisibility(JsonAutoDetect.Visibility.NONE)
.withCreatorVisibility(JsonAutoDetect.Visibility.NONE));

If you want it set globally, I usually access a configured mapper through a wrapper class.

Custom or dynamic @JsonProperty for all fields without annotation with Jackson

I was able to solve this with a custom extension of JacksonAnnotationIntrospector. I overrode the methods that look for @JsonProperty and provided my own logic. I also had to implement my own hasIgnoreMarker() to avoid placing @JsonIgnore all over the place because the filtering doesn't happen until the actual serialization so I was getting errors about duplicate getters and setters.

mapper.setAnnotationIntrospector(new MyAnnotationIntrospector());

private static class MyAnnotationIntrospector extends JacksonAnnotationIntrospector {


@Override
public PropertyName findNameForSerialization(Annotated a) {
if (a instanceof AnnotatedField) {
String name = a.getName();
if (name.endsWith("Attribute")) {
return PropertyName.construct(name.replace("Attribute", ""));
}
}
return super.findNameForSerialization(a);
}

@Override
public PropertyName findNameForDeserialization(Annotated a) {
if (a instanceof AnnotatedField) {
String name = a.getName();
if (name.endsWith("Attribute")) {
return PropertyName.construct(name.replace("Attribute", ""));
}
}
return super.findNameForDeserialization(a);
}


Related Topics



Leave a reply



Submit