0
点赞
收藏
分享

微信扫一扫

Spring同时支持Json和Xml

Mezereon 2021-09-28 阅读 65

Jar包引用

  • pom.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>

Java代码

  • 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;
}

使用

  • JSON
curl -X GET http://localhost:8080/user/2 -H 'Accept: application/json'
{
    "id": 2,
    "name": "name.2"
}
  • XML
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/jsonapplication/xml
  • Http status 415, Unsupported Media Type Content type '' not supported:因为服务器配置consumers={配置的内容},但是请求头中没有Content type,一般设置为application/jsonapplication/xml

参考

举报

相关推荐

0 条评论