Jackson配置
转换类(RequestParam 和 PathVariable)
编写类型 Date 的转换类
package com.luoqiz.pincheng.config.date;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.convert.converter.Converter;
import java.text.SimpleDateFormat;
import java.util.Date;
@Slf4j
public class StringToDateConverter implements Converter<String, Date> {
private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";
private static final String shortDateFormat = "yyyy-MM-dd";
private static final String timeStampFormat = "^\\d+$";
@Override
public Date convert(String value) {
if (value == null || value.trim().equals("") || value.equalsIgnoreCase("null")) {
return null;
}
value = value.trim();
try {
if (value.contains("-")) {
SimpleDateFormat formatter;
if (value.contains(":")) {
formatter = new SimpleDateFormat(dateFormat);
} else {
formatter = new SimpleDateFormat(shortDateFormat);
}
return formatter.parse(value);
} else if (value.matches(timeStampFormat)) {
Long lDate = Long.valueOf(value);
return new Date(lDate);
}
} catch (Exception e) {
throw new RuntimeException(String.format("parser %s to Date fail", value));
}
throw new RuntimeException(String.format("parser %s to Date fail", value));
}
}
编写类型 LocalDate 的转换类
package com.luoqiz.pincheng.config.date;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.convert.converter.Converter;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
@Slf4j
public class StringToLocalDateConverter implements Converter<String, LocalDate> {
private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";
private static final String shortDateFormat = "yyyy-MM-dd";
private static final String timeStampFormat = "^\\d+$";
@Override
public LocalDate convert(String value) {
if (value == null || value.trim().equals("") || value.equalsIgnoreCase("null")) {
return null;
}
value = value.trim();
try {
if (value.contains("-")) {
DateTimeFormatter formatter;
if (value.contains(":")) {
formatter = DateTimeFormatter.ofPattern(dateFormat);
} else {
formatter = DateTimeFormatter.ofPattern(shortDateFormat);
}
return LocalDate.parse(value, formatter);
} else if (value.matches(timeStampFormat)) {
Long timestamp = Long.valueOf(value);
return Instant.ofEpochMilli(timestamp).atZone(ZoneOffset.systemDefault()).toLocalDate();
}
} catch (Exception e) {
throw new RuntimeException(String.format("parser %s to LocalDate fail", value));
}
throw new RuntimeException(String.format("parser %s to LocalDate fail", value));
}
}
编写类型 LocalDateTime 的转换类
package com.luoqiz.pincheng.config.date;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.convert.converter.Converter;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
@Slf4j
public class StringToLocalDateTimeConverter implements Converter<String, LocalDateTime> {
private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";
private static final String timeStampFormat = "^\\d+$";
@Override
public LocalDateTime convert(String value) {
if (value == null || value.trim().equals("") || value.equalsIgnoreCase("null")) {
return null;
}
value = value.trim();
try {
if (value.contains("-")) {
return LocalDateTime.parse(value, DateTimeFormatter.ofPattern(dateFormat));
} else if (value.matches(timeStampFormat)) {
Long timestamp = Long.valueOf(value);
return Instant.ofEpochMilli(timestamp).atZone(ZoneOffset.systemDefault()).toLocalDateTime();
}
} catch (Exception e) {
throw new RuntimeException(String.format("parser %s to LocalDateTime fail", value));
}
throw new RuntimeException(String.format("parser %s to LocalDateTime fail", value));
}
}
配置
public class WebMvcConfig implements WebMvcConfigurer {
/**
* 添加自定义的Converters和Formatters.
*/
@Override
public void addFormatters(FormatterRegistry registry) {
registry.addConverter(new StringToDateConverter());
registry.addConverter(new StringToLocalDateConverter());
registry.addConverter(new StringToLocalDateTimeConverter());
}
}
序列化类(RequestBody)
转为字符串
package com.luoqiz.pincheng.config.date;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Date;
@Configuration
@Slf4j
public class DateConfig {
/**
* 默认日期时间格式
*/
public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
/**
* 默认日期格式
*/
public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
/**
* 默认时间格式
*/
public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";
private static final String timeStampFormat = "^\\d+$";
/**
* Json序列化和反序列化转换器,用于转换Post请求体中的json以及将我们的对象序列化为返回响应的json
*/
@Bean
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
//LocalDateTime系列序列化和反序列化模块,继承自jsr310,我们在这里修改了日期格式
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
//Date序列化和反序列化
javaTimeModule.addSerializer(Date.class, new JsonSerializer<Date>() {
@Override
public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
SimpleDateFormat formatter = new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT);
String formattedDate = formatter.format(date);
jsonGenerator.writeString(formattedDate);
}
});
javaTimeModule.addDeserializer(Date.class, new JsonDeserializer<Date>() {
@Override
public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
String value = jsonParser.getText();
if (value == null || value.trim().equals("") || value.equalsIgnoreCase("null")) {
return null;
}
if (value.matches(timeStampFormat)) {
Long timestamp = Long.valueOf(value);
return new Date(timestamp);
}
SimpleDateFormat format = new SimpleDateFormat(DEFAULT_DATE_TIME_FORMAT);
try {
return format.parse(value);
} catch (ParseException e) {
throw new RuntimeException(e);
}
}
});
objectMapper.registerModule(javaTimeModule);
return objectMapper;
}
}
转为时间戳
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalTimeSerializer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.time.format.DateTimeFormatter;
import java.util.Date;
/**
* @author luoqiz
*/
@Configuration
@Slf4j
public class DateConfig {
/**
* 默认日期时间格式
*/
public static final String DEFAULT_DATE_TIME_FORMAT = "yyyy-MM-dd HH:mm:ss";
/**
* 默认日期格式
*/
public static final String DEFAULT_DATE_FORMAT = "yyyy-MM-dd";
/**
* 默认时间格式
*/
public static final String DEFAULT_TIME_FORMAT = "HH:mm:ss";
private static final String timeStampFormat = "^\\d+$";
/**
* Json序列化和反序列化转换器,用于转换Post请求体中的json以及将我们的对象序列化为返回响应的json
*/
@Bean
@Primary
public ObjectMapper objectMapper() {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.disable(DeserializationFeature.ADJUST_DATES_TO_CONTEXT_TIME_ZONE);
//LocalDateTime系列序列化和反序列化模块,继承自jsr310,我们在这里修改了日期格式
JavaTimeModule javaTimeModule = new JavaTimeModule();
// javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
// javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
// javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
//
// javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_TIME_FORMAT)));
// javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern(DEFAULT_DATE_FORMAT)));
// javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
javaTimeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer());
javaTimeModule.addSerializer(LocalDate.class, new LocalDateSerializer());
javaTimeModule.addSerializer(LocalTime.class, new LocalTimeSerializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
javaTimeModule.addSerializer(Date.class, new DateSerializer());
javaTimeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer());
javaTimeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer());
javaTimeModule.addDeserializer(LocalTime.class, new LocalTimeDeserializer(DateTimeFormatter.ofPattern(DEFAULT_TIME_FORMAT)));
javaTimeModule.addDeserializer(Date.class, new DateDeserializer());
objectMapper.registerModule(javaTimeModule);
return objectMapper;
}
/**
* 序列化实现 Date 转为时间戳
*/
public static class DateSerializer extends JsonSerializer<Date> {
@Override
public void serialize(Date value, JsonGenerator gen, SerializerProvider serializers)
throws IOException {
if (value != null) {
long timestamp = value.getTime();
gen.writeNumber(timestamp);
}
}
}
/**
* 反序列化实现 时间戳转为 Date
*/
public static class DateDeserializer extends JsonDeserializer<Date> {
@Override
public Date deserialize(JsonParser p, DeserializationContext deserializationContext)
throws IOException {
long timestamp = p.getValueAsLong();
if (timestamp > 0) {
return new Date(timestamp);// .ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
} else {
return null;
}
}
}
/**
* 序列化实现 LocalDate 转为时间戳
*/
public static class LocalDateSerializer extends JsonSerializer<LocalDate> {
@Override
public void serialize(LocalDate value, JsonGenerator gen, SerializerProvider serializers)
throws IOException {
if (value != null) {
long timestamp = value.atStartOfDay(ZoneId.systemDefault()).toInstant().toEpochMilli();// .toEpochDay();// .atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
gen.writeNumber(timestamp);
}
}
}
/**
* 反序列化实现 时间戳转为 LocalDate
*/
public static class LocalDateDeserializer extends JsonDeserializer<LocalDate> {
@Override
public LocalDate deserialize(JsonParser p, DeserializationContext deserializationContext)
throws IOException {
long timestamp = p.getValueAsLong();
if (timestamp > 0) {
return Instant.ofEpochMilli(timestamp).atZone(ZoneId.systemDefault()).toLocalDate();// .ofInstant(Instant.ofEpochMilli(timestamp), ZoneId.systemDefault());
} else {
return null;
}
}
}
/**
* 序列化实现 LocalDateTime 转为时间戳
*/
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);
}
}
}
/**
* 反序列化实现 时间戳转为 LocalDateTime
*/
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 {
return null;
}
}
}
}
自定义解析类(无RequestParam、PathVariable、RequestBody)
编写 LocalDate 解析类
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import javax.servlet.http.HttpServletRequest;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
public class LocalDateHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter parameter) {
return LocalDate.class.equals(parameter.getParameterType());
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
ServletWebRequest servletWebRequest = (ServletWebRequest) webRequest;
HttpServletRequest httpServletRequest = servletWebRequest.getRequest();
String key = parameter.getParameter().getName();
String value = httpServletRequest.getParameter(key);
// 获取 contentType
// String contentType = httpServletRequest.getContentType();
// 获取支持媒体类型
// MediaType mediaType = MediaType.parseMediaType(contentType);
// Charset charset = mediaType.getCharset();
// charset = charset == null ? StandardCharsets.UTF_8 : charset;
// ServletInputStream in = httpServletRequest.getInputStream();
return convert(value);
}
private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";
private static final String shortDateFormat = "yyyy-MM-dd";
private static final String timeStampFormat = "^\\d+$";
public LocalDate convert(String value) {
if (value == null || value.trim().equals("") || value.equalsIgnoreCase("null")) {
return null;
}
value = value.trim();
try {
if (value.contains("-")) {
DateTimeFormatter formatter;
if (value.contains(":")) {
formatter = DateTimeFormatter.ofPattern(dateFormat);
} else {
formatter = DateTimeFormatter.ofPattern(shortDateFormat);
}
return LocalDate.parse(value, formatter);
} else if (value.matches(timeStampFormat)) {
Long timestamp = Long.valueOf(value);
return Instant.ofEpochMilli(timestamp).atZone(ZoneOffset.systemDefault()).toLocalDate();
}
} catch (Exception e) {
throw new RuntimeException(String.format("parser %s to LocalDate fail", value));
}
throw new RuntimeException(String.format("parser %s to LocalDate fail", value));
}
}
编写 LocalDateTime 解析类
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.context.request.ServletWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;
import javax.servlet.http.HttpServletRequest;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
public class LocalDateTimeHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter parameter) {
return LocalDateTime.class.equals(parameter.getParameterType());
}
@Override
public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
ServletWebRequest servletWebRequest = (ServletWebRequest) webRequest;
HttpServletRequest httpServletRequest = servletWebRequest.getRequest();
String key = parameter.getParameter().getName();
String value = httpServletRequest.getParameter(key);
return convert(value);
}
private static final String dateFormat = "yyyy-MM-dd HH:mm:ss";
private static final String timeStampFormat = "^\\d+$";
public LocalDateTime convert(String value) {
if (value == null || value.trim().equals("") || value.equalsIgnoreCase("null")) {
return null;
}
value = value.trim();
try {
if (value.contains("-")) {
return LocalDateTime.parse(value, DateTimeFormatter.ofPattern(dateFormat));
} else if (value.matches(timeStampFormat)) {
Long timestamp = Long.valueOf(value);
return Instant.ofEpochMilli(timestamp).atZone(ZoneOffset.systemDefault()).toLocalDateTime();
}
} catch (Exception e) {
throw new RuntimeException(String.format("parser %s to LocalDateTime fail", value));
}
throw new RuntimeException(String.format("parser %s to LocalDateTime fail", value));
}
}
配置
public class CommonWebMvcConfig implements WebMvcConfigurer {
/**
* 因为自定义的 HandlerMethodArgumentResolver,会放在
* {@link RequestMappingHandlerAdapter#customArgumentResolvers} 中,
* 而customArgumentResolvers自定义解析类会放在最后,为防止这种情况
* 所以放在 PostConstruct 中提升自定义的解析类位置
*/
@PostConstruct
public void init() {
// 获取已存在的参数解析类
List<HandlerMethodArgumentResolver> oldHandlerMethodArgumentResolver = requestMappingHandlerAdapter.getArgumentResolvers();
List<HandlerMethodArgumentResolver> newHandlerMethodArgumentResolver = new ArrayList<>(oldHandlerMethodArgumentResolver.size() + 1);
// 设置自定义的解析
newHandlerMethodArgumentResolver.add(new LocalDateHandlerMethodArgumentResolver());
newHandlerMethodArgumentResolver.addAll(oldHandlerMethodArgumentResolver);
requestMappingHandlerAdapter.setArgumentResolvers(newHandlerMethodArgumentResolver);
}
...
}
FastJson配置
转换类(RequestParam 和 PathVariable)和自定义解析类
同上
序列化类
@Configuration
public class JsonHttpMessageConverConfiguration {
@Primary
@Bean
@ConditionalOnProperty(name = { "spring.http.converters.preferred-json-mapper" }, havingValue = "fastJson")
@ConditionalOnMissingBean({ FastJsonHttpMessageConverter.class }) // 3
public HttpMessageConverter<?> fastJsonHttpMessageConverter() {
// 1、需要先定义一个 convert 转换消息的对象;
FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
List<MediaType> supportedMediaTypes = new ArrayList<>();
supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
supportedMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
supportedMediaTypes.add(MediaType.APPLICATION_PDF);
supportedMediaTypes.add(MediaType.IMAGE_GIF);
supportedMediaTypes.add(MediaType.IMAGE_JPEG);
supportedMediaTypes.add(MediaType.IMAGE_PNG);
// supportedMediaTypes.add(MediaType.TEXT_EVENT_STREAM);
// supportedMediaTypes.add(MediaType.TEXT_HTML);
supportedMediaTypes.add(MediaType.TEXT_MARKDOWN);
fastConverter.setSupportedMediaTypes(supportedMediaTypes);
// 2、添加fastJson 的配置信息,比如:是否要格式化返回的json数据;
FastJsonConfigExt fastJsonConfig = new FastJsonConfigExt();
// 修改配置返回内容的过滤
// WriteNullListAsEmpty :List字段如果为null,输出为[],而非null
// WriteNullStringAsEmpty : 字符类型字段如果为null,输出为"",而非null
// DisableCircularReferenceDetect :消除对同一对象循环引用的问题,默认为false(如果不配置有可能会进入死循环)
// WriteNullBooleanAsFalse:Boolean字段如果为null,输出为false,而非null
// WriteMapNullValue:是否输出值为null的字段,默认为false
// SerializerFeature.BrowserCompatible: 兼容浏览器,开启的话会将中文转为Unicode字符
fastJsonConfig.setSerializerFeatures(SerializerFeature.DisableCircularReferenceDetect,
SerializerFeature.PrettyFormat,
SerializerFeature.WriteMapNullValue);
//2、添加fastjson的配置信息,比如是否要格式化返回的json数据;
// FastJsonConfig fastJsonConfig=new FastJsonConfig();
// fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
////附加:处理中文乱码
// List<MediaType> fastMedisTypes = new ArrayList<MediaType>();
// fastMedisTypes.add(MediaType.APPLICATION_JSON_UTF8);
// fastConverter.setSupportedMediaTypes(fastMedisTypes);
////3、在convert中添加配置信息
// fastConverter.setFastJsonConfig(fastJsonConfig);
// converters.add(fastConverter);
// 设置null字段为字符串
// ValueFilter valueFilter = new ValueFilter() {// 5
// // o 是class
// // s 是key值
// // o1 是value值
// public Object process(Object o, String s, Object o1) {
// if (null == o1) {
// o1 = "";
// }
// return o1;
// }
// };
//设置数据过滤
// fastJsonConfig.setSerializeFilters(valueFilter);
// 3、在convert中添加配置信息.
fastConverter.setFastJsonConfig(fastJsonConfig);
return fastConverter;
}
}
FastJsonConfigExt.java
import com.alibaba.fastjson.parser.deserializer.Jdk8DateCodec;
import com.alibaba.fastjson.serializer.DateCodec;
import com.alibaba.fastjson.serializer.SerializeConfig;
import com.alibaba.fastjson.serializer.ToStringSerializer;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import java.math.BigInteger;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;
public class FastJsonConfigExt extends FastJsonConfig {
public FastJsonConfigExt() {
super();
SerializeConfig serializeConfig = SerializeConfig.globalInstance;
serializeConfig.put(BigInteger.class, ToStringSerializer.instance);
serializeConfig.put(Long.class, ToStringSerializer.instance);
serializeConfig.put(Long.TYPE, ToStringSerializer.instance);
serializeConfig.put(Date.class, DateCodec.instance);
serializeConfig.put(LocalDate.class, Jdk8DateCodec.instance);
serializeConfig.put(LocalDateTime.class, Jdk8DateCodec.instance);
this.setSerializeConfig(serializeConfig);
}
}