package com.czg.config;


import com.alibaba.fastjson2.JSONReader;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.support.config.FastJsonConfig;
import com.alibaba.fastjson2.support.spring6.http.converter.FastJsonHttpMessageConverter;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * fastjson2配置类
 *
 * @author tankaikai
 * @since 2025-02-11 18:14
 */
@Configuration
public class FastJson2Config implements WebMvcConfigurer {
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 创建 FastJson 消息转换器
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        // 创建 FastJson 配置
        FastJsonConfig config = new FastJsonConfig();
        // 设置日期格式
        config.setDateFormat("yyyy-MM-dd HH:mm:ss");

        // 设置反序列化特性
        config.setReaderFeatures(JSONReader.Feature.FieldBased, JSONReader.Feature.SupportArrayToBean);
        config.setWriterFeatures(
                JSONWriter.Feature.WriteMapNullValue,
                // 格式化输出
                JSONWriter.Feature.PrettyFormat,
                // Long类型序列化为字符串
                JSONWriter.Feature.WriteLongAsString,
                // String类型值为空序列化为""
                JSONWriter.Feature.WriteNullStringAsEmpty
        );

        // 将配置设置到转换器
        converter.setFastJsonConfig(config);
        // 设置字符编码
        converter.setDefaultCharset(StandardCharsets.UTF_8);
        // 设置支持的媒体类型
        List<MediaType> supportedMediaTypes = new ArrayList<>();
        supportedMediaTypes.add(MediaType.APPLICATION_JSON);
        converter.setSupportedMediaTypes(supportedMediaTypes);
        // 将转换器添加到 Spring MVC 的消息转换器列表中
        converters.addFirst(converter);
    }
}
