Spring接口XML转对象报错:Content type 'application/xml' not supported
问题描述
我有一个GET接口 localhost:8080/api/getPerson,需要将请求体映射为Person对象。发送JSON格式请求体时可正常返回结果,但发送XML格式请求体时,会返回**Unsupported Media Type(415)**状态码。
代码示例
package com.example.xml2object; import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestBody; @RestController @RequestMapping("api") public class Example { @JacksonXmlRootElement(localName = "person") public static class Person { public String name; } @GetMapping(value = "getPerson") public ResponseEntity<String> getPerson(@RequestBody Person person) { return ResponseEntity.ok(person.name); } }
正常请求(JSON)
设置Content-Type: application/json,发送请求体:
{ "name": "alice" }
返回预期结果:"alice"
错误请求(XML)
设置Content-Type: application/xml,发送请求体:
<?xml version="1.0"?> <person> <name>alice</name> </person>
收到415错误响应:
{ "timestamp": "2023-01-23T17:43:40.290+00:00", "path": "/api/getPerson", "status": 415, "error": "Unsupported Media Type", "message": "Content type 'application/xml' not supported for bodyType=com.example.xml2object.Example$Person", ... }
解决方案
1. 添加Jackson XML依赖
Spring默认仅包含JSON处理的Jackson依赖,XML解析需要额外引入jackson-dataformat-xml:
- Maven项目(
pom.xml):
<dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-xml</artifactId> </dependency>
- Gradle项目(
build.gradle):
implementation 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml'
2. 声明接口支持XML媒体类型
修改@GetMapping注解,显式指定允许的请求媒体类型,确保Spring能识别XML请求:
import org.springframework.http.MediaType; // ... @GetMapping(value = "getPerson", consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}) public ResponseEntity<String> getPerson(@RequestBody Person person) { return ResponseEntity.ok(person.name); }
3. 规范请求方法(可选但推荐)
HTTP规范中GET请求通常不携带请求体,部分服务器或代理会忽略该请求体。更稳妥的做法是将接口改为POST方法:
@PostMapping(value = "getPerson", consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}) public ResponseEntity<String> getPerson(@RequestBody Person person) { return ResponseEntity.ok(person.name); }
4. 确认实体类注解有效性
你已使用@JacksonXmlRootElement(localName = "person"),该注解能正确映射XML根节点,当前场景下无需额外调整;若后续实体类有嵌套字段,可补充@JacksonXmlElementWrapper或@JacksonXmlProperty注解优化映射逻辑。
内容的提问来源于stack exchange,提问作者Paniac
相关产品推荐
相关产品推荐

