【发布时间】: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..