SpringBoot默认Json解析框架jackson替换成fastjson,并使用全局日期格式化处理

SpringBoot默认Json解析框架jackson替换成fastjson,并使用全局日期格式化处理

1. 引入依赖

		<dependency>
			<groupId>com.alibabagroupId>
			<artifactId>fastjsonartifactId>
		dependency>

1.1编写配置类替换json解析

@Configuration
public class WebMvcConfig extends WebMvcConfigurationSupport {

    /** 
     * FastJson替换掉jackson,与加上全局日期格式转换,且解决中文乱码问题
     * 
     * @param converters  
     * @author: ZhiHao
     * @date: 2020/4/20 
     */
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    	// 清除默认 Json 转换器
        converters.removeIf(httpMessageConverter -> httpMessageConverter instanceof MappingJackson2HttpMessageConverter);
        //1.构建了一个HttpMessageConverter  FastJson   消息转换器
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        //2.定义一个配置,设置编码方式,和格式化的形式
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        //3.设置成了PrettyFormat格式
        fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat);
        //4.处理中文乱码问题
        List<MediaType> fastMediaTypes =  new ArrayList<>();
        fastMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastConverter.setSupportedMediaTypes(fastMediaTypes);
        //5.全局json请求日期反序列化 -->LocalDateTime
        ParserConfig parserConfig = new ParserConfig();
        parserConfig.putDeserializer(LocalDateTime.class,new MyLocalDateTimeDeserializer());
        fastJsonConfig.setParserConfig(parserConfig);
        //6.全局json响应日期序列化 -->LocalDateTime
        SerializeConfig serializeConfig = new SerializeConfig();
        serializeConfig.put(LocalDateTime.class,new MyLocalDateTimeSerializer("yyyy-MM-dd HH:mm:ss"));
        fastJsonConfig.setSerializeConfig(serializeConfig);
        //7.将fastJsonConfig加到消息转换器中
        fastConverter.setFastJsonConfig(fastJsonConfig);
        converters.add(fastConverter);
    }
}

1.2 编写MyLocalDateTimeSerializer

/**
 * @Author: zhihao
 * @Date: 2020/4/15 17:48
 * @Description: json响应 将日期字符串序列化为定制日期字符串响应
 * @Versions 1.0
 **/
public class MyLocalDateTimeSerializer extends SimpleDateFormatSerializer {

    private final String pattern;

    public MyLocalDateTimeSerializer(String pattern) {
        super(pattern);
        this.pattern = pattern;
    }

    @Override
    public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) throws IOException {
        if (object == null) {
            serializer.out.writeNull();
            return;
        }
        if (object instanceof LocalDateTime){
            LocalDateTime localDateTime = (LocalDateTime) object;
            String format = localDateTime.format(DateTimeFormatter.ofPattern(pattern));
            serializer.write(format);
        }
    }
}

1.3 编写MyLocalDateTimeDeserializer

/**
 * @Author: zhihao
 * @Date: 2020/4/15 17:08
 * @Description: json请求 将日期字符串反序列化为绑定到@requestBody对象上
 * @Versions 1.0
 **/
public class MyLocalDateTimeDeserializer extends AbstractDateDeserializer {

    private static final String YYYY_MM_DD = "yyyy-MM-dd";
    private static final String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";
    
    @Override
    protected <T> T cast(DefaultJSONParser parser, Type clazz, Object fieldName, Object value) {
        String dateStr = null;
        if (value instanceof  String){
            dateStr =  ((String) value);
        }else if (StringUtils.isBlank(dateStr)){
            return null;
        }
        //去前后空格
        dateStr = dateStr.trim();
        //判断是否yyyy-MM-dd格式
        if (dateStr.matches("^\\d{4}-\\d{1,2}-\\d{1,2}$")) {
            //yyyy-MM-dd 会构建成yyyy-MM-dd 00:00:00
            return (T) LocalDate.parse(dateStr, DateTimeFormatter.ofPattern(YYYY_MM_DD)).atStartOfDay();
            //判断是否yyyy-MM-dd HH:mm:ss格式
        } else if (dateStr.matches("^\\d{4}-\\d{1,2}-\\d{1,2} {1}\\d{1,2}:\\d{1,2}:\\d{1,2}$")) {
            return (T) LocalDateTime.parse(dateStr, DateTimeFormatter.ofPattern(YYYY_MM_DD_HH_MM_SS));
        } else {
            //都不匹配说明请求格式不正确
            throw new DateTimeException("Date Format IsWrong :" + dateStr);
        }
    }

    @Override
    public int getFastMatchToken() {
        return JSONToken.LITERAL_STRING;
    }
}

到此配置完成,自己测试过了, 可能有并不完善, 自己项目用的是jackson

你可能感兴趣的:(SpringBoot,SpringMVC,java,json)