SpringBoot返回Json和XML两种格式

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中每个接口的请求头,这种方式是指定该接口返回什么格式的数据

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

使用 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); //默认返回格式 
   }
}

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

 
            com.fasterxml.jackson.dataformat
            jackson-dataformat-xml
 

然后完美解决>

你可能感兴趣的:(Java)