当我们引入Eureka的时候, 项目的数据返回从Json变为了Xml,像下面这种
<User>
<userName>lee</userName>
<age>11</age>
<mobile>8090</mobile>
</User>
导致这个结果的根因是SpringBoot项目中集成了EurekaServer,又需要jackson-dataformat-xml这个依赖 ,而引入了这个依赖可以将实体转换为xml也可以转换为json,根据发起请求的request头中Accept来决定,我们发现请求头中都是xml的
Accept:text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Accept-Encoding:gzip, deflate, sdch, br
Accept-Language:zh-CN,zh;q=0.8
Cache-Control:max-age=0
Connection:keep-alive
Host:localhost:8091
Upgrade-Insecure-Requests:1
User-Agent:Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/57.0.2987.133 Safari/537.36
解决方案就是在我们的方法上的@GetMapping 或 @PostMappding 中加入一个produces = { “application/json;charset=UTF-8” }即可,会在响应头加入数据响应格式
Content-Type:application/json;charset=UTF-8
@GetMapping(value = "/getUserByName",produces = {"application/json;charset=UTF-8"})
public User getUser(@RequestParam(value = "username",defaultValue = "lee") String userName)
{
return userService.getUser(userName);
}
再次访问对应的访问路径发现成功变为jason格式
{"userName":"lee","age":11,"mobile":"8090"}