提供ObjectMapper
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
/**
* @author qhong
* @date 2021/11/5 12:20
**/
@Configuration
public class LocalDateTimeSerializerConfig {
/**
* 序列化LocalDateTime
*
* @return
*/
@Bean(value = "localDateTimeObjectMapper")
public ObjectMapper serializingObjectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
// 通過該方法對mapper對象進行設置,所有序列化的對象都將按改規則進行系列化
// Include.Include.ALWAYS 默認
// Include.NON_DEFAULT 屬性為默認值不序列化
// Include.NON_EMPTY 屬性為 空("") 或者為 NULL 都不序列化,則返回的json是沒有這個字段的。這樣對移動端會更省流量
// Include.NON_NULL 屬性為NULL 不序列化
objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
// 允許忽略多傳入的字段,直接忽略
objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
// 允許出現特殊字符和轉義符
objectMapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
// 允許出現單引號
objectMapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
// 兼容反斜杠,允許接受引號引起來的所有字符
objectMapper.configure(JsonParser.Feature.ALLOW_BACKSLASH_ESCAPING_ANY_CHARACTER, true);
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer());
javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer());
objectMapper.registerModule(javaTimeModule);
return objectMapper;
}
/**
* 序列化實現
*/
public static class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
@Override
public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers)
throws IOException {
if (value != null) {
long timestamp = value.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
gen.writeNumber(timestamp);
}
}
}
/**
* 反序列化實現
*/
public static class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
@Override
public LocalDateTime deserialize(JsonParser p, DeserializationContext deserializationContext)
throws IOException {
long timestamp = p.getValueAsLong();
if (timestamp > 0) {
return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
} else {
//兼容字符串格式時間傳入
String value = p.getValueAsString();
return LocalDateTimeUtil.of(DateUtil.parse(value));
}
}
}
}
可以直接使用@Primary,強制整個系統使用上面的ObjectMapper,但是會出現與其他jar定義ObjectMapper沖突
提供MappingJackson2HttpMessageConverter
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import javax.annotation.Resource;
import java.nio.charset.Charset;
import java.util.LinkedList;
import java.util.List;
/**
* @author qhong
* @date 2022/4/14 19:52
**/
@Configuration
public class MessageConverterConfig {
@Resource(name = "localDateTimeObjectMapper")
public ObjectMapper objectMapper;
/**
* 使用jackson序列化消息轉換
*/
@Bean
public MappingJackson2HttpMessageConverter fastJsonHttpMessageConverters() {
MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
messageConverter.setDefaultCharset(Charset.defaultCharset());
messageConverter.setObjectMapper(objectMapper);
//支持的媒體類型
List<MediaType> supportedMediaTypes = new LinkedList<>();
supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
//頁面直接請求的類型(這里是新增加的支持的匹配的類型,頁面訪問的時候類型為text/html)
supportedMediaTypes.add(MediaType.TEXT_HTML);
messageConverter.setSupportedMediaTypes(supportedMediaTypes);
//@formatter:on
return messageConverter;
}
}
入參時間戳轉換為LocalDateTime
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import javax.annotation.Resource;
import java.util.List;
/**
* @author qhong
* @date 2022/4/14 19:50
**/
@Configuration
public class MessageConverterOrderWebMvcConfigurer implements WebMvcConfigurer {
@Resource
private MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter;
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
//方法一:把jackson解析器放在第一位,這樣匹配完了之后,就會直接返回;[是否匹配和我們解析器支持的類型有關[supportedMediaTypes]詳細見源碼
// org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor#writeWithMessageConverters]
converters.add(0, mappingJackson2HttpMessageConverter);
}
}
返回體LocalDateTime轉換為時間戳
import com.alibaba.fastjson.JSONObject;
import com.qhong.test.common.ResultBase;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
/**
* @author qhong
* @date 2022/4/14 19:50
**/
@Slf4j
//這里盡量讓加密的判斷優先級更低一點(請求的時候,加密的優先級高一點
@Order(1)
@RestControllerAdvice
public class ResponseHandle implements ResponseBodyAdvice<Object> {
@Autowired
private MappingJackson2HttpMessageConverter mappingJackson2HttpMessageConverter;
/**
* 是否支持此消息響應處理器
*
* @return boolean
* @Param methodParameter
* @Param aClass
* @author peikunkun
* @date 2021/1/6 0006 下午 4:29
* @since
*/
@Override
public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
return true;
}
/**
* 在選擇HttpMessageConverter之后且在調用其write方法之前調用。
* <p>
* 參數:正文–要寫的正文
* returnType –控制器方法的返回類型
* selectedContentType –通過內容協商選擇的內容類型
* selectedConverterType –選擇要寫入響應的轉換器類型
* 請求–當前請求
* 響應–當前響應
* 返回值:
* 傳入的正文或經過修改的(可能是新的)實例
*/
@SneakyThrows
@Override
public Object beforeBodyWrite(Object resBody, MethodParameter methodParameter, MediaType mediaType,
Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest,
ServerHttpResponse serverHttpResponse) {
try {
if (resBody instanceof ResultBase) {
return JSONObject.parseObject(mappingJackson2HttpMessageConverter.getObjectMapper().writeValueAsString(resBody), ResultBase.class);
}
} catch (Exception e) {
log.warn("ResponseHandle Return Error", e);
}
return resBody;
}
}