Spring Boot入門——json數據處理


1、引入fastJson插件

<!-- 引入fastjson插件 -->
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>fastjson</artifactId>
        <version>1.2.32</version>
    </dependency>
  
  <!-- 打包插件 -->
  <build>
      <plugins>
          <plugin>
              <groupId>org.springframework.boot</groupId>
              <artifactId>spring-boot-maven-plugin</artifactId>
              <configuration>
                  <fork>true</fork><!-- 熱部署生效必須加 -->
              </configuration>
          </plugin>
      </plugins>
  </build>

2、兩種方法實現

  2.1、在App.java文件中實現HttpMessageConverters

 

  @Bean
    public HttpMessageConverters fastJsonConverters(){
        FastJsonHttpMessageConverter fastJsonConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastConf = new FastJsonConfig();
        
        fastConf.setSerializerFeatures(SerializerFeature.PrettyFormat);
        fastJsonConverter.setFastJsonConfig(fastConf);
        
        HttpMessageConverter<?> converter = fastJsonConverter;
        return new HttpMessageConverters(converter);    
    }

 

  2.2、在App.java類繼承WebMvcConfigurerAdapter類,並重寫configureMessageConverters方法

 

@SpringBootApplication
public class App extends WebMvcConfigurerAdapter{
    public static void main( String[] args )
    {
        System.out.println( "Hello World!" );
        SpringApplication.run(App.class, args);
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        // TODO Auto-generated method stub
        super.configureMessageConverters(converters);
        
        FastJsonHttpMessageConverter fastJsonConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastConf = new FastJsonConfig();
        
        fastConf.setSerializerFeatures(SerializerFeature.PrettyFormat);
        fastJsonConverter.setFastJsonConfig(fastConf);
        
        converters.add(fastJsonConverter);
    }
    
    
    /*@Bean
    public HttpMessageConverters fastJsonConverters(){
        FastJsonHttpMessageConverter fastJsonConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastConf = new FastJsonConfig();
        
        fastConf.setSerializerFeatures(SerializerFeature.PrettyFormat);
        fastJsonConverter.setFastJsonConfig(fastConf);
        
        HttpMessageConverter<?> converter = fastJsonConverter;
        return new HttpMessageConverters(converter);    
    }*/
    
    
}

3、格式化屬性的值

 

    private String userId;
    private String userName;
    
    @JSONField(format="yyyy-MM-dd")
    private Date createDate;    

 

4、測試

  格式化之前

  

  格式化之后

  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM