前言
我们提供接口给前端,或者是其他应用系统,又或者是与第三方对接的时候,总会以json或者是xml的方式与对方交互,本文将介绍使用spring-boot的时候,如何将想响应自动转换为json或者xml格式的字符串
手动调用第三方库转换
最笨的方法是直接将DTO对象转成string类型后返回,如下所示:
@RequestMapping("/test1")
@ResponseBody
public String fastjson() {
Map<String, Object> res = new HashMap<>();
res.put("site", "debugcn.com");
res.put("title", "DebugCN");
return JSON.toJSONString(res);
}
调用返回:
$ curl localhost:8080/test1
{"site":"debugcn.com","title":"DebugCN"}
直接返回dto
其实不需要自己将其转换为json,框架自己已经做好了相关的处理:
@RequestMapping("/test2")
@ResponseBody
public Map<String, Object> json() {
Map<String, Object> res = new HashMap<>();
res.put("site", "debugcn.com");
res.put("title", "DebugCN");
return res;
}
调用返回:
$ curl localhost:8080/test2
{"site":"debugcn.com","title":"DebugCN"}
返回XML
假如我想返回xml该怎么办呢,百度出来的都是各种老掉牙的方法,其实spring-boot早就提供了相关的注解:
你可以使用produces注解,标注这个方法返回的是xml格式的数据
@RequestMapping(value = "/test3", produces = MediaType.APPLICATION_ATOM_XML_VALUE)
@ResponseBody
public Map<String, Object> xml() {
Map<String, Object> res = new HashMap<>();
res.put("site", "debugcn.com");
res.put("title", "DebugCN");
return res;
}
光是这样还不够,那还需要添加jackson与xml相关的依赖:
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>
这样就可以调用了:
$ curl localhost:8080/test3
<Map><site>debugcn.com</site><title>DebugCN</title></Map>
既能返回json又能返回xml
有同学说,这不是扯淡吗,怎么可能一个接口既能返回json又能返回xml?其实我们可以利用http协议请求头中的accept,其实spring-boot的controller已经做好支持了,不需要我们写一行代码,我们回到第一个示例:
@RequestMapping("/test2")
@ResponseBody
public Map<String, Object> json() {
Map<String, Object> res = new HashMap<>();
res.put("site", "debugcn.com");
res.put("title", "DebugCN");
return res;
}
我们在请求头中增加 accept:application/xml
,然后再调用:
$ curl -H "accept:application/xml" localhost:8080/test2
<Map><site>debugcn.com</site><title>DebugCN</title></Map
神奇的一幕发生了。
总结
本文介绍了如何在spring-boot的controller中返回json以及xml格式的数据,并没有网上那些所谓的教程那么复杂,spring-boot已经为你做好了一切。
文章评论