我使用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..
答案 0 :(得分:11)
您正在使用XStream序列化XML响应,并使用Jackson JSON来序列化JSON响应。查看您发布的JSON输出,似乎有一个循环引用问题。我猜Entity
有一个属性列表,每个属性都指向它们各自的实体。 XStream通过使用XPath透明地处理循环引用,这允许在反序列化返回到对象时保留引用。自v1.6起,Jackson能够处理循环引用,但您需要通过@JsonManagedReference
和@JsonBackReference
注释序列化实体来帮助它。我认为杰克逊在允许JSON序列化中的返回引用方面是独一无二的。
请参阅杰克逊关于handling bi-directional references using declarative methods的文档以供参考。