package com.ktg.framework.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
@EnableWebMvc
public class WebMvcConfig implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 配置StringHttpMessageConverter（如果需要的话）
        converters.add(new StringHttpMessageConverter());

        Jackson2ObjectMapperBuilder builder = new Jackson2ObjectMapperBuilder();
        // 忽略序列化时null字段的显示
        // builder.serializationInclusion(JsonInclude.Include.NON_NULL);
        ObjectMapper objectMapper = builder.build();

        SimpleModule simpleModule = new SimpleModule();
        // 为Long类型注册ToStringSerializer，将其序列化为字符串
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        objectMapper.registerModule(simpleModule);

        // 将配置好的ObjectMapper添加到MappingJackson2HttpMessageConverter中
        converters.add(new MappingJackson2HttpMessageConverter(objectMapper));

        // 如果继承了其他WebMvcConfigurer实现类，可以调用super.configureMessageConverters(converters);
        // 但在这个例子中，我们并没有继承其他实现类，所以不需要调用
    }
}
