Reputation: 4774
I have class with @JsonIgnore-d
field:
public class MyClass {
...
@JsonIgnore
private SomeType myfield;
...
// getters & setters
}
Is it possible to configure ObjectWriter
so that it includes myfield
during serialization even though being ingored?
Rationale: MyClass is serialized in many places and only in single specific one I want to have myfield
.
Upvotes: 14
Views: 3826
Reputation: 81
One more option is to use the AnnotationIntrospector.nopInstance() if you want to avoid all Jackson's annotations in your pojo including @JsonIgnore e.g.
JsonMapper.builder().annotationIntrospector(AnnotationIntrospector.nopInstance()).build()...
or
new ObjectMapper().setAnnotationIntrospector(AnnotationIntrospector.nopInstance())...
Upvotes: 1
Reputation: 11619
It is possible to configure ObjectMapper
to disable a JsonIgnore function. Following are some possible solution you can try with:
1. Disable JsonIgnore function for a particular annotated field.
You can create a custom JsonIgnore annotation and a custom JacksonAnnotationIntrospector
to remove the annotation from mapper context.
Following are the ideas:
Annotate @MyJsonIgnore
to the fields that should be ignored while serialization:
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
public class MyClass {
@MyJsonIgnore
private SomeType myField;
}
@MyJsonIgnore
is a simple custom annotation that wrap @JsonIgnore
:
@Retention(RetentionPolicy.RUNTIME)
@JacksonAnnotationsInside
@JsonIgnore
public @interface MyJsonIgnore {
}
A custom JacksonAnnotationIntrospector
is implemented to remove @MyJsonIgnore
from mapper context:
public class DisablingMyJsonIgnoreIntrospector extends JacksonAnnotationIntrospector {
@Override
public boolean isAnnotationBundle(final Annotation ann) {
if (ann.annotationType().equals(MyJsonIgnore.class)) {
return false;
} else {
return super.isAnnotationBundle(ann);
}
}
After that, you can set the introspector on a ObjectMapper
during configuration:
ObjectMapper mapper = new ObjectMapper();
mapper.setAnnotationIntrospector(new DisablingMyJsonIgnoreIntrospector());
It results that the fields annotated with @MyJsonIgnore
can be marshaled properly.
2. Disable JsonIgnore function for the mapper
Your can create a custom JacksonAnnotationIntrospector
and override hasIgnoreMarker
method to always return false
:
public static class DisablingJsonIgnoreIntrospector extends JacksonAnnotationIntrospector {
@Override
public boolean hasIgnoreMarker(final AnnotatedMember m) {
return false;
}
}
hasIgnoreMarker
is to check whether there is annotation to ignore json property. Return false
will disable the JsonIngore function.
3.
Disable all annotations and specify what kinds of properties are auto-detected for a given ObjectMapper
:
final ObjectMapper mapper = new ObjectMapper();
mapper.disable(MapperFeature.USE_ANNOTATIONS);
mapper.setVisibility(PropertyAccessor.FIELD, JsonAutoDetect.Visibility.ANY);
This simply disable all annotations.
Hope this can help.
Upvotes: 27