由於項目需要,同一接口支持根據參數不同返回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("000000"); } }
這個主要就是修改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