Spring 3:@ResponseBody - 如何控制响应以获取 XML 或 JSON?
我正在使用
Spring (3.0) 配置(没有 ContentNegotiatingViewResolver)。根据 文档 Spring 3 支持 JSON 和 XML。在如下处理程序方法上使用 @ResponseBody
会给出 JSON 响应。如何控制响应以获取 XML 或 JSON ?
@RequestMapping("/data")
public @ResponseBody User getUser() {
return new User();
}
编辑
使用的Maven依赖项:
<!-- xml -->
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.1.8</version>
</dependency>
<!-- json -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.8.1</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.8.1</version>
</dependency>
调试AnnotationDrivenBeanDefinitionParser =>; jaxb2Present = true,jacksonPresent = true
I'm using <mvc:annotation-driven />
Spring (3.0) configuration (without ContentNegotiatingViewResolver). According to the documentation Spring 3 supports JSON and XML. Using @ResponseBody
on handler method like below gives JSON response. How to control the response to get the XML or JSON ?
@RequestMapping("/data")
public @ResponseBody User getUser() {
return new User();
}
EDIT
Used Maven dependencies:
<!-- xml -->
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.1.8</version>
</dependency>
<!-- json -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.8.1</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.8.1</version>
</dependency>
Debugging AnnotationDrivenBeanDefinitionParser => jaxb2Present = true, jacksonPresent = true
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
Spring 使用请求的“Accept”标头来决定是发送 JSON 还是 XML。如果两者都被接受,那么你会得到一个或另一个,我不记得首先被检查。
要获取 XML,您的客户端需要在标头中包含“application/xml”,而不是“application/json”。
Spring uses the "Accept" header of the request to decide whether to send JSON or XML. If both are accepted, then you you'll get one or the other, I can't remember gets checked first.
To get an XML, your client needs to have "application/xml" in the header, rather than "application/json ".
像这样使用@ResponseBody。下面的方法将 JSON 作为请求参数并返回 JSON 响应。
Use
@ResponseBody
like this. Method below takes JSON as request parameter and returns JSON response.它在RequestMapping中配置
It's configured in RequestMapping