Spring REST | MappingJacksonHttpMessageConverter生成无效的JSON

Sri*_*Sri 6 java rest spring json

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

  <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>
Run Code Online (Sandbox Code Playgroud)

这是我的控制器方法:

@Controller
@RequestMapping(value = "/entityService")
class RestfulEntityService {

  @Resource
  private EntityService entityService;

  @ResponseBody
  @RequestMapping(value = "/getAllEntities", method = RequestMethod.GET)
  public List<Entity> getAllEntities() {
    return entityService.getAllEntities();
  }
}
Run Code Online (Sandbox Code Playgroud)

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..
Run Code Online (Sandbox Code Playgroud)

Oph*_*itz 12

您正在使用XStream来序列化XML响应,使用Jackson JSON来序列化JSON响应.查看您发布的JSON输出,似乎有一个循环引用问题.我猜Entity有一个属性列表,每个属性都指向它们各自的实体.XStream通过使用XPath透明地处理循环引用,这允许在反序列化返回到对象时保留引用.从v1.6开始,Jackson能够处理循环引用,但你需要通过使用@JsonManagedReference和注释序列化实体来帮助它@JsonBackReference.我认为杰克逊在允许JSON序列化中的返回引用方面是独一无二的.

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