I’m having trouble getting Jackson mixins working for embedded types when using @ResponseBody. I’m using spring MVC 3.0 and jackson 1.8.
I have an object called EventEntry. That object has a property user, returning the type User via the getUser method. I set up mixins for both EventEntry and User. The mixins just consist of lots of @JasonIgnoreProperties values.
When an EventEntry is streamed out, the mixin is correctly applied and many properties are ignored. However, when the User object that is part of the EventEntry object is streamed out, the mixin is not applied and all properties are returned.
Code below:
public class EventEntry {
private User user;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
}
The user class has lots of properties, most of which I do not want to return as part of the json object.
In my controller, I add the mixins I want to user as below:
@RequestMapping(value = "/event/view/{eventIdentifier}/entries/json", method = RequestMethod.GET)
public @ResponseBody List<EventEntry> viewMyEventsJson(HttpServletResponse response, @PathVariable("eventIdentifier") String eventIdentifier){
ObjectMapper mapper = new ObjectMapper();
SerializationConfig serializationConfig = mapper.getSerializationConfig();
serializationConfig.addMixInAnnotations(EventEntry.class, BasicEventEntryJsonMixin.class);
serializationConfig.addMixInAnnotations(User.class, BasicPublicUserJsonMixin.class);
List<EventEntry> eventEntryList = getEventEntries(eventIdentifier);
try {
mapper.writValue(response.getOutputStream(), eventEntryList);
} catch (IOException ex) {
logger.error(ex);
}
return null;
}
I have added two mixins, one for EventEntry, the other for User. As before, EventEntry contains a getUser() method.
Both mixins simply contain a whole lot of @JsonIgnoreProperty values:
@JsonIgnoreProperties({"eventId","lastUpdatedOn","lastUpdatedBy"})
public class BasicEventEntryJsonMixin extends EventEntry{
//Empty by design
}
@JsonIgnoreProperties({"emailAddress","lastUpdatedOn","lastUpdatedBy"})
public class BasicPublicUserJsonMixin extends User {
}
The mixin for EventEntry is correctly applied, but the mixin for the User is not – the entire object is streamed out.
The only config I have for jackson is
<bean id="messageAdapter" class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<!-- Support JSON -->
<bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
</list>
</property>
</bean>
Do mixins not apply to embedded objects or have I misconfigured something?
Also, is there a neater way to achieve what I want to do which is essentially to decided on a view-by-view basis which properties should be returned and which shouldn’t?
The reason is that you configure one Jackson Mapper, but use an other one (the one from Spring).
Do it this way:
then you even do not need the xml configuration