1. 程式人生 > >Spring Boot默認的JSON解析框架設置

Spring Boot默認的JSON解析框架設置

nconf ext 類繼承 fast spa fig ati ast bean

方案一:啟動類繼承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一下

Spring Boot默認的JSON解析框架設置