Spring同时支持Json和Xml

/ Java / 没有评论 / 1885浏览

项目中有时候需要同时支持XML和JSON格式的参数和返回值,如果是参数还比较容易处理,可以用String接收然后手动转换。 但是如果是返回值,则需要使用Spring框架自动转换,本文介绍如何在Spring框架实现Json和Xml

Jar包引用

<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>

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();
    }
}
@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>

常见问题

参考