Spring REST | MappingJacksonHttpMessageConverter生成无效的JSON

我用Spring实现了一个RESTful Web服务。 该服务基于Accept标头以XML或JSON响应。 这是context.xml映射:

                 

这是我的控制器方法:

 @Controller @RequestMapping(value = "/entityService") class RestfulEntityService { @Resource private EntityService entityService; @ResponseBody @RequestMapping(value = "/getAllEntities", method = RequestMethod.GET) public List getAllEntities() { return entityService.getAllEntities(); } } 

XML响应是有效的,但是,当客户端将Accept标头设置为application / json时,响应是无效的JSON。

这是JSON响应示例:

 [{"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输出,看起来手头有一个循环引用问题。 我猜测Entity有一个属性列表,每个属性都指向它们各自的实体。 XStream通过使用XPath透明地处理循环引用,这允许在反序列化返回到对象时保留引用。 从v1.6开始,Jackson能够处理循环引用,但是你需要通过@JsonManagedReference@JsonBackReference来注释你的序列化实体来帮助它。 我认为Jackson在允许JSON序列化中的引用方面是独一无二的。

请参阅Jackson关于使用声明方法处理双向引用的文档以供参考。