Jackson配置

转换类(RequestParam 和 PathVariable)

编写类型 Date 的转换类

  1. package com.luoqiz.pincheng.config.date;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.springframework.core.convert.converter.Converter;
  4. import java.text.SimpleDateFormat;
  5. import java.util.Date;
  6. @Slf4j
  7. public class StringToDateConverter implements Converter<String, Date> {
  8. private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";
  9. private static final String shortDateFormat = "yyyy-MM-dd";
  10. private static final String timeStampFormat = "^\\d+$";
  11. @Override
  12. public Date convert(String value) {
  13. if (value == null || value.trim().equals("") || value.equalsIgnoreCase("null")) {
  14. return null;
  15. }
  16. value = value.trim();
  17. try {
  18. if (value.contains("-")) {
  19. SimpleDateFormat formatter;
  20. if (value.contains(":")) {
  21. formatter = new SimpleDateFormat(dateFormat);
  22. } else {
  23. formatter = new SimpleDateFormat(shortDateFormat);
  24. }
  25. return formatter.parse(value);
  26. } else if (value.matches(timeStampFormat)) {
  27. Long lDate = Long.valueOf(value);
  28. return new Date(lDate);
  29. }
  30. } catch (Exception e) {
  31. throw new RuntimeException(String.format("parser %s to Date fail", value));
  32. }
  33. throw new RuntimeException(String.format("parser %s to Date fail", value));
  34. }
  35. }

编写类型 LocalDate 的转换类

  1. package com.luoqiz.pincheng.config.date;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.springframework.core.convert.converter.Converter;
  4. import java.time.Instant;
  5. import java.time.LocalDate;
  6. import java.time.ZoneOffset;
  7. import java.time.format.DateTimeFormatter;
  8. @Slf4j
  9. public class StringToLocalDateConverter implements Converter<String, LocalDate> {
  10. private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";
  11. private static final String shortDateFormat = "yyyy-MM-dd";
  12. private static final String timeStampFormat = "^\\d+$";
  13. @Override
  14. public LocalDate convert(String value) {
  15. if (value == null || value.trim().equals("") || value.equalsIgnoreCase("null")) {
  16. return null;
  17. }
  18. value = value.trim();
  19. try {
  20. if (value.contains("-")) {
  21. DateTimeFormatter formatter;
  22. if (value.contains(":")) {
  23. formatter = DateTimeFormatter.ofPattern(dateFormat);
  24. } else {
  25. formatter = DateTimeFormatter.ofPattern(shortDateFormat);
  26. }
  27. return LocalDate.parse(value, formatter);
  28. } else if (value.matches(timeStampFormat)) {
  29. Long timestamp = Long.valueOf(value);
  30. return Instant.ofEpochMilli(timestamp).atZone(ZoneOffset.systemDefault()).toLocalDate();
  31. }
  32. } catch (Exception e) {
  33. throw new RuntimeException(String.format("parser %s to LocalDate fail", value));
  34. }
  35. throw new RuntimeException(String.format("parser %s to LocalDate fail", value));
  36. }
  37. }

编写类型 LocalDateTime 的转换类

  1. package com.luoqiz.pincheng.config.date;
  2. import lombok.extern.slf4j.Slf4j;
  3. import org.springframework.core.convert.converter.Converter;
  4. import java.time.Instant;
  5. import java.time.LocalDateTime;
  6. import java.time.ZoneOffset;
  7. import java.time.format.DateTimeFormatter;
  8. @Slf4j
  9. public class StringToLocalDateTimeConverter implements Converter<String, LocalDateTime> {
  10. private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";
  11. private static final String timeStampFormat = "^\\d+$";
  12. @Override
  13. public LocalDateTime convert(String value) {
  14. if (value == null || value.trim().equals("") || value.equalsIgnoreCase("null")) {
  15. return null;
  16. }
  17. value = value.trim();
  18. try {
  19. if (value.contains("-")) {
  20. return LocalDateTime.parse(value, DateTimeFormatter.ofPattern(dateFormat));
  21. } else if (value.matches(timeStampFormat)) {
  22. Long timestamp = Long.valueOf(value);
  23. return Instant.ofEpochMilli(timestamp).atZone(ZoneOffset.systemDefault()).toLocalDateTime();
  24. }
  25. } catch (Exception e) {
  26. throw new RuntimeException(String.format("parser %s to LocalDateTime fail", value));
  27. }
  28. throw new RuntimeException(String.format("parser %s to LocalDateTime fail", value));
  29. }
  30. }

配置

  1. public class WebMvcConfig implements WebMvcConfigurer {
  2. /**
  3. * 添加自定义的Converters和Formatters.
  4. */
  5. @Override
  6. public void addFormatters(FormatterRegistry registry) {
  7. registry.addConverter(new StringToDateConverter());
  8. registry.addConverter(new StringToLocalDateConverter());
  9. registry.addConverter(new StringToLocalDateTimeConverter());
  10. }
  11. }

序列化类(RequestBody)

转为字符串

  1. package com.luoqiz.pincheng.config.date;
  2. import com.fasterxml.jackson.core.JsonGenerator;
  3. import com.fasterxml.jackson.core.JsonParser;
  4. import com.fasterxml.jackson.core.JsonProcessingException;
  5. import com.fasterxml.jackson.databind.*;
  6. import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
  7. import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
  8. import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
  9. import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
  10. import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
  11. import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
  12. import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
  13. import lombok.extern.slf4j.Slf4j;
  14. import org.springframework.context.annotation.Bean;
  15. import org.springframework.context.annotation.Configuration;
  16. import java.io.IOException;
  17. import java.text.ParseException;
  18. import java.text.SimpleDateFormat;
  19. import java.time.*;
  20. import java.time.format.DateTimeFormatter;
  21. import java.util.Date;
  22. @Configuration
  23. @Slf4j
  24. public class DateConfig {
  25. /**
  26. * 默认日期时间格式
  27. */
  28. public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
  29. /**
  30. * 默认日期格式
  31. */
  32. public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
  33. /**
  34. * 默认时间格式
  35. */
  36. public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";
  37. private static final String timeStampFormat = "^\\d+$";
  38. /**
  39. * Json序列化和反序列化转换器,用于转换Post请求体中的json以及将我们的对象序列化为返回响应的json
  40. */
  41. @Bean
  42. public ObjectMapper objectMapper() {
  43. ObjectMapper objectMapper = new ObjectMapper();
  44. objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
  45. objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
  46. //LocalDateTime系列序列化和反序列化模块,继承自jsr310,我们在这里修改了日期格式
  47. JavaTimeModule javaTimeModule = new JavaTimeModule();
  48. javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
  49. javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
  50. javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
  51. javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
  52. javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
  53. javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
  54. //Date序列化和反序列化
  55. javaTimeModule.addSerializer(Date.class, new JsonSerializer<Date>() {
  56. @Override
  57. public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
  58. SimpleDateFormat formatter = new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT);
  59. String formattedDate = formatter.format(date);
  60. jsonGenerator.writeString(formattedDate);
  61. }
  62. });
  63. javaTimeModule.addDeserializer(Date.class, new JsonDeserializer<Date>() {
  64. @Override
  65. public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
  66. String value = jsonParser.getText();
  67. if (value == null || value.trim().equals("") || value.equalsIgnoreCase("null")) {
  68. return null;
  69. }
  70. if (value.matches(timeStampFormat)) {
  71. Long timestamp = Long.valueOf(value);
  72. return new Date(timestamp);
  73. }
  74. SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT);
  75. try {
  76. return format.parse(value);
  77. } catch (ParseException e) {
  78. throw new RuntimeException(e);
  79. }
  80. }
  81. });
  82. objectMapper.registerModule(javaTimeModule);
  83. return objectMapper;
  84. }
  85. }

转为时间戳

  1. import com.fasterxml.jackson.core.JsonGenerator;
  2. import com.fasterxml.jackson.core.JsonParser;
  3. import com.fasterxml.jackson.core.JsonProcessingException;
  4. import com.fasterxml.jackson.databind.*;
  5. import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
  6. import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
  7. import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
  8. import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
  9. import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
  10. import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
  11. import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
  12. import lombok.extern.slf4j.Slf4j;
  13. import org.springframework.context.annotation.Bean;
  14. import org.springframework.context.annotation.Configuration;
  15. import org.springframework.context.annotation.Primary;
  16. import java.io.IOException;
  17. import java.text.ParseException;
  18. import java.text.SimpleDateFormat;
  19. import java.time.*;
  20. import java.time.format.DateTimeFormatter;
  21. import java.util.Date;
  22. /**
  23. * @author luoqiz
  24. */
  25. @Configuration
  26. @Slf4j
  27. public class DateConfig {
  28. /**
  29. * 默认日期时间格式
  30. */
  31. public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
  32. /**
  33. * 默认日期格式
  34. */
  35. public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
  36. /**
  37. * 默认时间格式
  38. */
  39. public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";
  40. private static final String timeStampFormat = "^\\d+$";
  41. /**
  42. * Json序列化和反序列化转换器,用于转换Post请求体中的json以及将我们的对象序列化为返回响应的json
  43. */
  44. @Bean
  45. @Primary
  46. public ObjectMapper objectMapper() {
  47. ObjectMapper objectMapper = new ObjectMapper();
  48. objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
  49. objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
  50. //LocalDateTime系列序列化和反序列化模块,继承自jsr310,我们在这里修改了日期格式
  51. JavaTimeModule javaTimeModule = new JavaTimeModule();
  52. // javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
  53. // javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
  54. // javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
  55. //
  56. // javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
  57. // javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
  58. // javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
  59. javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer());
  60. javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer());
  61. javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
  62. javaTimeModule.addSerializer(Date.class, new DateSerializer());
  63. javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer());
  64. javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer());
  65. javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
  66. javaTimeModule.addDeserializer(Date.class, new DateDeserializer());
  67. objectMapper.registerModule(javaTimeModule);
  68. return objectMapper;
  69. }
  70. /**
  71. * 序列化实现 Date 转为时间戳
  72. */
  73. public static class DateSerializer extends JsonSerializer<Date> {
  74. @Override
  75. public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers)
  76. throws IOException {
  77. if (value != null) {
  78. long timestamp = value.getTime();
  79. gen.writeNumber(timestamp);
  80. }
  81. }
  82. }
  83. /**
  84. * 反序列化实现 时间戳转为 Date
  85. */
  86. public static class DateDeserializer extends JsonDeserializer<Date> {
  87. @Override
  88. public Date deserialize(JsonParser p, DeserializationContext deserializationContext)
  89. throws IOException {
  90. long timestamp = p.getValueAsLong();
  91. if (timestamp > 0) {
  92. return new Date(timestamp);// .ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
  93. } else {
  94. return null;
  95. }
  96. }
  97. }
  98. /**
  99. * 序列化实现 LocalDate 转为时间戳
  100. */
  101. public static class LocalDateSerializer extends JsonSerializer<LocalDate> {
  102. @Override
  103. public void serialize(LocalDate value, JsonGenerator gen, SerializerProvider serializers)
  104. throws IOException {
  105. if (value != null) {
  106. long timestamp = value.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli();// .toEpochDay();// .atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
  107. gen.writeNumber(timestamp);
  108. }
  109. }
  110. }
  111. /**
  112. * 反序列化实现 时间戳转为 LocalDate
  113. */
  114. public static class LocalDateDeserializer extends JsonDeserializer<LocalDate> {
  115. @Override
  116. public LocalDate deserialize(JsonParser p, DeserializationContext deserializationContext)
  117. throws IOException {
  118. long timestamp = p.getValueAsLong();
  119. if (timestamp > 0) {
  120. return Instant.ofEpochMilli(timestamp).atZone(ZoneId.systemDefault()).toLocalDate();// .ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
  121. } else {
  122. return null;
  123. }
  124. }
  125. }
  126. /**
  127. * 序列化实现 LocalDateTime 转为时间戳
  128. */
  129. public static class LocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
  130. @Override
  131. public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers)
  132. throws IOException {
  133. if (value != null) {
  134. long timestamp = value.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
  135. gen.writeNumber(timestamp);
  136. }
  137. }
  138. }
  139. /**
  140. * 反序列化实现 时间戳转为 LocalDateTime
  141. */
  142. public static class LocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
  143. @Override
  144. public LocalDateTime deserialize(JsonParser p, DeserializationContext deserializationContext)
  145. throws IOException {
  146. long timestamp = p.getValueAsLong();
  147. if (timestamp > 0) {
  148. return LocalDateTime.ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
  149. } else {
  150. return null;
  151. }
  152. }
  153. }
  154. }

自定义解析类(无RequestParam、PathVariable、RequestBody)

编写 LocalDate 解析类

  1. import org.springframework.core.MethodParameter;
  2. import org.springframework.web.bind.support.WebDataBinderFactory;
  3. import org.springframework.web.context.request.NativeWebRequest;
  4. import org.springframework.web.context.request.ServletWebRequest;
  5. import org.springframework.web.method.support.HandlerMethodArgumentResolver;
  6. import org.springframework.web.method.support.ModelAndViewContainer;
  7. import javax.servlet.http.HttpServletRequest;
  8. import java.time.Instant;
  9. import java.time.LocalDate;
  10. import java.time.ZoneOffset;
  11. import java.time.format.DateTimeFormatter;
  12. public class LocalDateHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
  13. @Override
  14. public boolean supportsParameter(MethodParameter parameter) {
  15. return LocalDate.class.equals(parameter.getParameterType());
  16. }
  17. @Override
  18. public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
  19. ServletWebRequest servletWebRequest = (ServletWebRequest) webRequest;
  20. HttpServletRequest httpServletRequest = servletWebRequest.getRequest();
  21. String key = parameter.getParameter().getName();
  22. String value = httpServletRequest.getParameter(key);
  23. // 获取 contentType
  24. // String contentType = httpServletRequest.getContentType();
  25. // 获取支持媒体类型
  26. // MediaType mediaType = MediaType.parseMediaType(contentType);
  27. // Charset charset = mediaType.getCharset();
  28. // charset = charset == null ? StandardCharsets.UTF_8 : charset;
  29. // ServletInputStream in = httpServletRequest.getInputStream();
  30. return convert(value);
  31. }
  32. private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";
  33. private static final String shortDateFormat = "yyyy-MM-dd";
  34. private static final String timeStampFormat = "^\\d+$";
  35. public LocalDate convert(String value) {
  36. if (value == null || value.trim().equals("") || value.equalsIgnoreCase("null")) {
  37. return null;
  38. }
  39. value = value.trim();
  40. try {
  41. if (value.contains("-")) {
  42. DateTimeFormatter formatter;
  43. if (value.contains(":")) {
  44. formatter = DateTimeFormatter.ofPattern(dateFormat);
  45. } else {
  46. formatter = DateTimeFormatter.ofPattern(shortDateFormat);
  47. }
  48. return LocalDate.parse(value, formatter);
  49. } else if (value.matches(timeStampFormat)) {
  50. Long timestamp = Long.valueOf(value);
  51. return Instant.ofEpochMilli(timestamp).atZone(ZoneOffset.systemDefault()).toLocalDate();
  52. }
  53. } catch (Exception e) {
  54. throw new RuntimeException(String.format("parser %s to LocalDate fail", value));
  55. }
  56. throw new RuntimeException(String.format("parser %s to LocalDate fail", value));
  57. }
  58. }

编写 LocalDateTime 解析类

  1. import org.springframework.core.MethodParameter;
  2. import org.springframework.web.bind.support.WebDataBinderFactory;
  3. import org.springframework.web.context.request.NativeWebRequest;
  4. import org.springframework.web.context.request.ServletWebRequest;
  5. import org.springframework.web.method.support.HandlerMethodArgumentResolver;
  6. import org.springframework.web.method.support.ModelAndViewContainer;
  7. import javax.servlet.http.HttpServletRequest;
  8. import java.time.Instant;
  9. import java.time.LocalDateTime;
  10. import java.time.ZoneOffset;
  11. import java.time.format.DateTimeFormatter;
  12. public class LocalDateTimeHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
  13. @Override
  14. public boolean supportsParameter(MethodParameter parameter) {
  15. return LocalDateTime.class.equals(parameter.getParameterType());
  16. }
  17. @Override
  18. public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
  19. ServletWebRequest servletWebRequest = (ServletWebRequest) webRequest;
  20. HttpServletRequest httpServletRequest = servletWebRequest.getRequest();
  21. String key = parameter.getParameter().getName();
  22. String value = httpServletRequest.getParameter(key);
  23. return convert(value);
  24. }
  25. private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";
  26. private static final String timeStampFormat = "^\\d+$";
  27. public LocalDateTime convert(String value) {
  28. if (value == null || value.trim().equals("") || value.equalsIgnoreCase("null")) {
  29. return null;
  30. }
  31. value = value.trim();
  32. try {
  33. if (value.contains("-")) {
  34. return LocalDateTime.parse(value, DateTimeFormatter.ofPattern(dateFormat));
  35. } else if (value.matches(timeStampFormat)) {
  36. Long timestamp = Long.valueOf(value);
  37. return Instant.ofEpochMilli(timestamp).atZone(ZoneOffset.systemDefault()).toLocalDateTime();
  38. }
  39. } catch (Exception e) {
  40. throw new RuntimeException(String.format("parser %s to LocalDateTime fail", value));
  41. }
  42. throw new RuntimeException(String.format("parser %s to LocalDateTime fail", value));
  43. }
  44. }

配置

  1. public class CommonWebMvcConfig implements WebMvcConfigurer {
  2. /**
  3. * 因为自定义的 HandlerMethodArgumentResolver,会放在
  4. * {@link RequestMappingHandlerAdapter#customArgumentResolvers} 中,
  5. * 而customArgumentResolvers自定义解析类会放在最后,为防止这种情况
  6. * 所以放在 PostConstruct 中提升自定义的解析类位置
  7. */
  8. @PostConstruct
  9. public void init() {
  10. // 获取已存在的参数解析类
  11. List<HandlerMethodArgumentResolver> oldHandlerMethodArgumentResolver = requestMappingHandlerAdapter.getArgumentResolvers();
  12. List<HandlerMethodArgumentResolver> newHandlerMethodArgumentResolver = new ArrayList<>(oldHandlerMethodArgumentResolver.size() + 1);
  13. // 设置自定义的解析
  14. newHandlerMethodArgumentResolver.add(new LocalDateHandlerMethodArgumentResolver());
  15. newHandlerMethodArgumentResolver.addAll(oldHandlerMethodArgumentResolver);
  16. requestMappingHandlerAdapter.setArgumentResolvers(newHandlerMethodArgumentResolver);
  17. }
  18. ...
  19. }

FastJson配置

转换类(RequestParam 和 PathVariable)和自定义解析类

同上

序列化类

  1. @Configuration
  2. public class JsonHttpMessageConverConfiguration {
  3. @Primary
  4. @Bean
  5. @ConditionalOnProperty(name = { "spring.http.converters.preferred-json-mapper" }, havingValue = "fastJson")
  6. @ConditionalOnMissingBean({ FastJsonHttpMessageConverter.class }) // 3
  7. public HttpMessageConverter<?> fastJsonHttpMessageConverter() {
  8. // 1、需要先定义一个 convert 转换消息的对象;
  9. FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
  10. List<MediaType> supportedMediaTypes = new ArrayList<>();
  11. supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
  12. supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
  13. supportedMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
  14. supportedMediaTypes.add(MediaType.APPLICATION_PDF);
  15. supportedMediaTypes.add(MediaType.IMAGE_GIF);
  16. supportedMediaTypes.add(MediaType.IMAGE_JPEG);
  17. supportedMediaTypes.add(MediaType.IMAGE_PNG);
  18. // supportedMediaTypes.add(MediaType.TEXT_EVENT_STREAM);
  19. // supportedMediaTypes.add(MediaType.TEXT_HTML);
  20. supportedMediaTypes.add(MediaType.TEXT_MARKDOWN);
  21. fastConverter.setSupportedMediaTypes(supportedMediaTypes);
  22. // 2、添加fastJson 的配置信息,比如:是否要格式化返回的json数据;
  23. FastJsonConfigExt fastJsonConfig = new FastJsonConfigExt();
  24. // 修改配置返回内容的过滤
  25. // WriteNullListAsEmpty :List字段如果为null,输出为[],而非null
  26. // WriteNullStringAsEmpty : 字符类型字段如果为null,输出为"",而非null
  27. // DisableCircularReferenceDetect :消除对同一对象循环引用的问题,默认为false(如果不配置有可能会进入死循环)
  28. // WriteNullBooleanAsFalse:Boolean字段如果为null,输出为false,而非null
  29. // WriteMapNullValue:是否输出值为null的字段,默认为false
  30. // SerializerFeature.BrowserCompatible: 兼容浏览器,开启的话会将中文转为Unicode字符
  31. fastJsonConfig.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect,
  32. SerializerFeature.PrettyFormat,
  33. SerializerFeature.WriteMapNullValue);
  34. //2、添加fastjson的配置信息,比如是否要格式化返回的json数据;
  35. // FastJsonConfig fastJsonConfig=new FastJsonConfig();
  36. // fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
  37. ////附加:处理中文乱码
  38. // List<MediaType> fastMedisTypes = new ArrayList<MediaType>();
  39. // fastMedisTypes.add(MediaType.APPLICATION_JSON_UTF8);
  40. // fastConverter.setSupportedMediaTypes(fastMedisTypes);
  41. ////3、在convert中添加配置信息
  42. // fastConverter.setFastJsonConfig(fastJsonConfig);
  43. // converters.add(fastConverter);
  44. // 设置null字段为字符串
  45. // ValueFilter valueFilter = new ValueFilter() {// 5
  46. // // o 是class
  47. // // s 是key值
  48. // // o1 是value值
  49. // public Object process(Object o, String s, Object o1) {
  50. // if (null == o1) {
  51. // o1 = "";
  52. // }
  53. // return o1;
  54. // }
  55. // };
  56. //设置数据过滤
  57. // fastJsonConfig.setSerializeFilters(valueFilter);
  58. // 3、在convert中添加配置信息.
  59. fastConverter.setFastJsonConfig(fastJsonConfig);
  60. return fastConverter;
  61. }
  62. }

FastJsonConfigExt.java

  1. import com.alibaba.fastjson.parser.deserializer.Jdk8DateCodec;
  2. import com.alibaba.fastjson.serializer.DateCodec;
  3. import com.alibaba.fastjson.serializer.SerializeConfig;
  4. import com.alibaba.fastjson.serializer.ToStringSerializer;
  5. import com.alibaba.fastjson.support.config.FastJsonConfig;
  6. import java.math.BigInteger;
  7. import java.time.LocalDate;
  8. import java.time.LocalDateTime;
  9. import java.util.Date;
  10. public class FastJsonConfigExt extends FastJsonConfig {
  11. public FastJsonConfigExt() {
  12. super();
  13. SerializeConfig serializeConfig = SerializeConfig.globalInstance;
  14. serializeConfig.put(BigInteger.class, ToStringSerializer.instance);
  15. serializeConfig.put(Long.class, ToStringSerializer.instance);
  16. serializeConfig.put(Long.TYPE, ToStringSerializer.instance);
  17. serializeConfig.put(Date.class, DateCodec.instance);
  18. serializeConfig.put(LocalDate.class, Jdk8DateCodec.instance);
  19. serializeConfig.put(LocalDateTime.class, Jdk8DateCodec.instance);
  20. this.setSerializeConfig(serializeConfig);
  21. }
  22. }