package com.ym.im.config;

import com.fasterxml.jackson.databind.Module;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.module.SimpleModule;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.ym.im.util.JsonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;

/**
 * @author 陈俊雄
 * @date 2019/5/30
 **/
@Configuration
public class JacksonConfig {
    @Autowired
    private ObjectMapper objectMapper;

    @PostConstruct
    public void init() {
        // Date类型对象转时间戳（毫秒数）
        objectMapper.enable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
        objectMapper.registerModule(getSerializerLong2String());
        objectMapper.registerModule(getSerializerDouble2String());
        JsonUtils.setObjectMapper(objectMapper);
    }

    /**
     * 将Long类型字段转Json字符串时转换为String类型防止前端Js精度丢失
     *
     * @return simpleModule
     */
    public Module getSerializerLong2String() {
        final SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);
        return simpleModule;
    }

    /**
     * 将Double类型字段转Json字符串时转换为String类型防止前端Js精度丢失
     *
     * @return simpleModule
     */
    public Module getSerializerDouble2String() {
        final SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Double.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Double.TYPE, ToStringSerializer.instance);
        return simpleModule;
    }
}
