package top.imwork.window.silos.config;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import java.io.IOException;

/**
 * Copyright (C), 2015-2021
 * FileName: JacksonConfig
 * Author(作者姓名):   jiangxiaowei
 * CreateDate(创建时间):     2021/8/2 15:35
 * UpdateDate(修改时间):     2021/8/2 15:35
 * Description(功能描述):    JacksonConfig
 * Since(版本号)  1.0.0
 * History:
 */
@Configuration
public class JacksonConfig {
    @Bean
    @Primary
    public ObjectMapper objectMapper() {
        ObjectMapper mapper = new ObjectMapper();

        // 处理 Long 类型
        SimpleModule module = new SimpleModule();
        module.addSerializer(Long.class, new JsonSerializer<Long>() {
            @Override
            public void serialize(Long value, JsonGenerator gen,
                                  SerializerProvider serializers) throws IOException {
                gen.writeString(value.toString());
            }
        });

        // 处理 long 基本类型
        module.addSerializer(Long.TYPE, new JsonSerializer<Long>() {
            @Override
            public void serialize(Long value, JsonGenerator gen,
                                  SerializerProvider serializers) throws IOException {
                gen.writeString(value.toString());
            }
        });

        mapper.registerModule(module);
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        return mapper;
    }
}
