当前位置: 首页 > 图灵资讯 > 技术篇> @RestController注解开发问题排查

@RestController注解开发问题排查

来源:图灵教育
时间:2023-04-19 16:05:07

  问题@Restcontroller注释,对于返回值为集合API接口,其数据仍将系列化为XML格式调查的原因经调查发现,spring-cloud-starter-netflix-eureka-client的Maven依赖间接引入jackson-dataformat-xml包,如果springhttp信息转换器(HttpMessageConverter)使用这个包会,然后它会根据http请求头上的Accept来决定是返回XML还是JSON。然而,目前大多数浏览器默认的Accept值都是“没有额外设置的”text/html,application/xhtml+xml,application/xml“,这使得当我们直接浏览地址栏访问接口时,我们期望返回JSON返回XML,因为JSON和XML格式可以互转! 解决方案 如果您的应用程序不再需要返回xml系列格式,然后直接在pom.jackson在xml文件中-dataformat-排除xml外包(如果其他包也是jackson)-dataformat-也应根据情况排除xml的依赖引用): org.springframework.cloud spring-cloud-starter-netflix-eureka-client 2.2.3.RELEASE com.fasterxml.jackson.dataformat jackson-dataformat-xml 二是不排除jackson-dataformat-xml包,但直接在相应的接口方法或Controller上明确指定将返回JSON格式的值: @GetMapping(value = "/user-instance", produces = MediaType.APPLICATION_PROBLEM_JSON_VALUE) public List showUserServiceInfo() { return this.discoveryClient.getInstances("provider-user-metadata"); } 第三种:也可以添加自定义的Springhttp信息转换器(HttpMessageConverter)定制返回值系列化的方法是实现WebMvconfigurer,重写configuremessageconverters方法,例如,用阿里的Fastjson转换http信息:/** * 自定义配置的信息转换器,将阿里云的FastJson消息转换器添加到当前的HTTP消息转换器列表中 * * @param converters 目前HTTP消息转换器列表的对象 */ @Override public void configureMessageConverters(List> converters) { FastJsonHttpMessageConverter fastJsonConverter = new FastJsonHttpMessageConverter(); FastJsonConfig fastJsonConfig = new FastJsonConfig(); fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat); fastJsonConfig.setCharset(Charset.forName(GB2312);///解决中文系列后的乱码 fastJsonConverter.setFastJsonConfig(fastJsonConfig); //converters.add(fastJsonConverter);///这将使fastJsonConverter排在新闻转换器管道列表的最后,它可能无法处理信息转换 converters.add(0, fastJsonConverter);///显示将fastJsonConverter列入新闻转换器管道列表的第一位 }导包: com.alibaba fastjson 1.2.70