• Spring Boot默认的JSON解析框架设置


    方案一:启动类继承WebMvcConfigurerAdapter,覆盖方法configureMessageConverters

    ...
    @SpringBootApplication
    public class UserApplication extends WebMvcConfigurerAdapter{
     
      @Override
      public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        super.configureMessageConverters(converters);
     
        // 初始化转换器
        FastJsonHttpMessageConverter fastConvert = new FastJsonHttpMessageConverter();
        // 初始化一个转换器配置
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
     //用于美化格式,可注释掉   fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
        // 将配置设置给转换器并添加到HttpMessageConverter转换器列表中
        fastConvert.setFastJsonConfig(fastJsonConfig);
     
        converters.add(fastConvert);
      }
     
      public static void main(String[] args) {
        SpringApplication.run(UserApplication.class, args);
      }
    }

    方案二:在启动类中注入 HttpMessageConverters

    ...
    @SpringBootApplication
    public class UserApplication {
        /**
         * 配置FastJson为Spring Boot默认JSON解析框架
         * @return  HttpMessageConverters
         */
        @Bean
        public HttpMessageConverters fastJsonHttpMessageConverters() {
            // 1.定义一个converters转换消息的对象
            FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
            // 2.添加fastjson的配置信息,比如: 是否需要格式化返回的json数据
            FastJsonConfig fastJsonConfig = new FastJsonConfig();
            fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
            // 3.在converter中添加配置信息
            fastConverter.setFastJsonConfig(fastJsonConfig);
            // 4.将converter赋值给HttpMessageConverter
            HttpMessageConverter<?> converter = fastConverter;
            // 5.返回HttpMessageConverters对象
            return new HttpMessageConverters(converter);
        }
        public static void main(String[] args) {
            SpringApplication.run(UserApplication.class, args);
        }
    }

    mark一下

  • 相关阅读:
    01
    Django2
    Django01
    DS18B20时序解析,以及读出85原因诠释
    python字符串打印-不同方法vars
    2.对象属性
    1.excel-vba-对象
    搭建 eclipse,maven,tomcat 环境
    jsp include flush true
    oracle数据库基础
  • 原文地址:https://www.cnblogs.com/wujh88/p/10333785.html
Copyright © 2020-2023  润新知