【问题标题】:Spring REST | MappingJacksonHttpMessageConverter produces invalid JSON弹簧休息 | MappingJacksonHttpMessageConverter 产生无效的 JSON
【发布时间】:2011-08-02 13:59:54
【问题描述】:

我已经使用 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>

这是我的控制器方法:

@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 响应示例:

[{"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..

【问题讨论】:

  • 可能值得发布一个完全有效和完全无效的回复
  • 无效响应很大(有效响应也是如此),因为它必须序列化 100 个实体的列表。我发布的无效回复只是重复了一百次并停止了..
  • 有趣的是,一个包含一两个实体的小列表被正确序列化为 JSON..

标签: java json spring rest


【解决方案1】:

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

请参阅 Jackson 在 handling bi-directional references using declarative methods 上的文档以供参考。

【讨论】:

  • 听起来很有希望……让我试试吧!
猜你喜欢
  • 2018-07-25
  • 1970-01-01
  • 1970-01-01
  • 2014-02-28
  • 1970-01-01
  • 2018-07-13
  • 1970-01-01
  • 2018-12-27
相关资源
最近更新 更多