springBoot序列化的方式有,fastJosn和jackson兩種一般:
一、springBoot默認的是jackson:
當使用jackson時,返回的json和數據庫會相差8個小時,(親測);
數據庫和postman相差8個小時,debug後發現是jackson得問題。
如果要解決這種問題,用文件配置可以解決
#application.properties文件配置
spring.jackson.time-zone=GMT+8
------------------------------------
#application.yml文件配置
spring:
jackson:
time-zone: GMT+8
或者這樣也可以解決,在你的時間上設置時間格式化。
public class Vo {
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss",timezone="GMT+8")
private Date createTime;
}
二、設置爲FasJson;
如果想SpringBoot默認使用FastJson,一般有兩種方式:
方式一、啓動類繼承WebMvcConfigurerAdapter ,複寫configureMessageConverters
/**
* 在這裏我們使用@SpringBootApplication指定這是一個 spring boot的應用程序.
*/
@SpringBootApplication
public class App extends WebMvcConfigurerAdapter {
// 第一種方式配置使用FstJson
@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
super.configureMessageConverters(converters);
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(
SerializerFeature.PrettyFormat
);
fastConverter.setFastJsonConfig(fastJsonConfig);
converters.add(fastConverter);
}
public static void main(String[] args) {
SpringApplication.run(App.class, args);
}
}
方式二、添加Bean到Spring容器,進行管理
package com.config;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.web.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
/**
* 設置config類 使用 @Bean注入 fastJsonHttpMessageConvert
*/
@Configuration
public class MassageConverConfiguration {
@Bean
public HttpMessageConverters fastJsonHttpMessageConverters() {
// 1、需要先定義一個 convert 轉換消息的對象;
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
// 2、添加fastJson 的配置信息,比如:是否要格式化返回的json數據;
FastJsonConfig fastJsonConfig = new FastJsonConfig();
fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
// 3、在convert中添加配置信息.
fastConverter.setFastJsonConfig(fastJsonConfig);
HttpMessageConverter<?> converter = fastConverter;
return new HttpMessageConverters(converter);
}
}