返回Json和XML两种格式

2023-04-22,,

由于项目需要,同一接口支持根据参数不同返回XML和Json两种格式的数据,在网上看了很多大多是加后缀的方式来实现返回不同格式数据的,后来看了一篇http://www.importnew.com/27632.html    挺不错,而且讲解的很细致

(一) 返回不同格式的几种方式

        1) 改变请求后缀的方式改变返回格式

http://localhost:8080/login.xml

http://localhost:8080/login.json

        2) 以参数的方式要求返回不同的格式

http://localhost:8080/login?format=json

http://localhost:8080/login?format=xml

        3) 直接在修改controller中每个接口的请求头,这种方式是指定该接口返回什么格式的数据

                       返回XML

            @GetMapping(value = "/findByUsername",produces = { "application/xml;charset=UTF-8" })

返回Json

@GetMapping(value = "/findByUsername",produces = { "application/json;charset=UTF-8" })

(二) 使用 1 、 2 两种方式

          主要就只有一个配置

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport { @Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer.favorPathExtension(true) //是否支持后缀的方式
.favorParameter(true) //是否支持请求参数的方式
.parameterName("format") //请求参数名
.defaultContentType(MediaType.APPLICATION_ATOM_XML); //默认返回格式
}
}

有了这个配置之后,基本上第一种第二种都实现了,请求的时候json没有问题,但是XML返回是空的,没有任何返回,这是因为你项目中没有xml的解析,

在pom.xml中加上

        <dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
</dependency>

然后完美解决

方案一

方案二

(三) 第三种,指定返回格式

    @GetMapping(value = "/findByUsername",produces = { "application/xml;charset=UTF-8" })
public ResponseResult findByUsername(String username){
if ("admin".equals(username)){
User user = new User();
user.setUsername(username);
user.setCity("中国");
user.setSex("女");
return new ResponseResult().setData(user);
}else {
return new ResponseResult("");
}
}

这个主要就是修改mapping注解中的produces = { "application/xml;charset=UTF-8" }

但是切记,第三种方式和前两种方式不能同时存在,当你加入了配置之后再使用第三种方式会导致找不到这个路径,所以你自己看吧

(四) 在SpringBoot中在yml中配置

 

spring:
mvc:
contentnegotiation:
#favor-path-extension: true #这个配置了但是不能使用,具体原因未知,这里就直接注释了
favor-parameter: true
parameter-name: Format

使用这个配置的方式可以不用写代码了,但是在灵活性上要稍微差一点,但是如果你追求简洁,这种方式又恰好能满足你的需求,这也是个不错的选择

https://github.com/SunArmy/result  这是在写的时候一边写博客一边写Demo

返回Json和XML两种格式的相关教程结束。

《返回Json和XML两种格式.doc》

下载本文的Word格式文档,以方便收藏与打印。