Reputation: 189
Is there a way to define which JsonView is used by default when serializing an object?
I have three views, DefaultView, UserView, and AdminView. Right now if I do not specifically set a view to use, it will include all fields from Default, User, and Admin views.
I would like it to only include fields from DefaultView unless I explicitly mark my rest endpoint with @JsonView(UserView.class/AdminView.class).
Upvotes: 2
Views: 1859
Reputation: 189
The view used for serialization can be set with the following code:
objectMapper.setConfig(objectMapper.getSerializationConfig().withView(DefaultView.class));
I ended up removing DefaultView. Any fields that belonged to a specialized view I continued to annotate with @JsonView(UserView.class/AdminView.class). Any fields I didn't ever want serialized I marked as @JsonIgnore.
I utilized the following ObjectMapper config to get my desired results:
@Provider
public class JacksonContextResolver implements ContextResolver<ObjectMapper> {
private final ObjectMapper objectMapper;
public JacksonContextResolver() {
objectMapper = new ObjectMapper();
objectMapper.setConfig(objectMapper.getSerializationConfig().withView(Object.class));
objectMapper.enable(MapperFeature.DEFAULT_VIEW_INCLUSION);
}
@Override
public ObjectMapper getContext(Class<?> arg0) {
return objectMapper;
}
}
Upvotes: 3