Spring REST | MappingJacksonHttpMessageConverter produces invalid JSON
我用Spring实现了一个RESTful Web服务。服务根据accept头以XML或JSON响应。以下是context.xml映射:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <bean id="xstreamMarshaller" class="org.springframework.oxm.xstream.XStreamMarshaller"/> <bean id="xmlMessageConverter" class="org.springframework.http.converter.xml.MarshallingHttpMessageConverter"> <constructor-arg ref="xstreamMarshaller"/> <property name="supportedMediaTypes" value="application/xml"/> </bean> <bean id="jsonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"> <property name="prefixJson" value="false"/> <property name="supportedMediaTypes" value="application/json"/> </bean> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <util:list id="beanList"> <ref bean="xmlMessageConverter"/> <ref bean="jsonHttpMessageConverter"/> </util:list> </property> </bean> |
以下是我的控制器方法:
1 2 3 4 5 6 7 8 9 10 11 12 13 | @Controller @RequestMapping(value ="/entityService") class RestfulEntityService { @Resource private EntityService entityService; @ResponseBody @RequestMapping(value ="/getAllEntities", method = RequestMethod.GET) public List<Entity> getAllEntities() { return entityService.getAllEntities(); } } |
号
XML响应是有效的,但是,当客户机将accept头设置为application/json时,响应是无效的json。
下面是JSON响应示例:
1 | [{"id":3,"attributes":[{"id":18,"attributeValue":null,"attributeName":"mobile","attributeType":"varchar(40)","entity":{"id":3,"attributes":[{"id":18,"attributeValue":null,"attributeName":"mobile","attributeType":"varchar(40)","entity":{"id":3,"attributes":[{"id":18,"attributeValue":null,"attributeName":"mobile","attributeType":"varchar(40)","entity":{"id":3,"attributes": ..... repeats for a while and then stops.. |
您正在使用XStream序列化XML响应,而Jackson JSON序列化JSON响应。查看您发布的JSON输出,似乎有一个循环引用问题。我猜
请参阅Jackson关于使用声明性方法处理双向引用的文档以获取参考。