json - Spring3 REST Web Services with Jackson JSONViews -
i got plain spring3 web project set , have controller method this:
@requestmapping(method = requestmethod.get, value = "/book/{id}", headers = "accept=application/json,application/xml") public @responsebody book getbook(@pathvariable final string id) { logger.warn("id=" + id); return new book("12345", new date(), "sven haiges"); }
it returns new book object transformed json or xml because of transformers setup in spring config:
<bean class="org.springframework.web.servlet.mvc.annotation.annotationmethodhandleradapter"> <property name="messageconverters"> <list> <ref bean="jsonconverter" /> <ref bean="marshallingconverter" /> </list> </property> </bean>
json generation (and xml) works, able define multiple views data. example i'd specify detailed view less properties in exposed json/xml , detailed view full set of properties.
using jackson's objectmapper possible this:
objectmapper.writevalueusingview(out, beaninstance, viewspublic.class);
is there way can configure spring use specific view (detailed/summary)? way achieve right use different dtos returned controller methods.
thanx!
if need level of control, need yourself.
so rather using @responsebody
, instead use own objectmapper
write response manually, e.g.
private final objectmapper objectmapper = new objectmapper(); @requestmapping(method = requestmethod.get, value = "/book/{id}", headers = "accept=application/json,application/xml") public void getbook(@pathvariable final string id, httpservletresponse httpresponse) { logger.warn("id=" + id); book book = new book("12345", new date(), "sven haiges"); objectmapper.writevalueusingview(httpresponse.getwriter(), book, viewspublic.class); }
by way, writevalueusingview
deprecated in current version of json (see javadoc).
Comments
Post a Comment