项目中有时候需要同时支持XML和JSON格式的参数和返回值,如果是参数还比较容易处理,可以用String接收然后手动转换。 但是如果是返回值,则需要使用Spring框架自动转换,本文介绍如何在Spring框架实现Json和Xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
UserController.java
@RestController
@RequestMapping("user")
public class UserController {
@GetMapping(path = "/{id}", produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
public User getUser(@PathVariable Integer id) {
return User.builder().id(id).name("name." +id).build();
}
}
User.java
@Data
@Builder
public class User {
private Integer id;
private String name;
}
curl -X GET http://localhost:8080/user/2 -H 'Accept: application/json'
{
"id": 2,
"name": "name.2"
}
curl -X GET http://localhost:8080/user/2 -H 'Accept: application/xml'
<User>
<id>2</id>
<name>name.2</name>
</User>
Http status 406
:请求中的Accept
头不合法,或者不被服务器接受,一遍修改为application/json
或application/xml
Http status 415
, Unsupported Media Type
Content type '' not supported
:因为服务器配置consumers={配置的内容}
,但是请求头中没有Content type
,一般设置为application/json
或application/xml