JacksonMapperConfig.java 2.23 KB
package cn.com.glsx.smart.config;

import javax.annotation.PostConstruct;
import java.text.SimpleDateFormat;
import java.util.Map;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.jackson.JacksonProperties;
import org.springframework.context.annotation.Configuration;

/**
 * <p>Description: 用于配置 jackson 序列化和反序列化
 * <p>Project: chejia-smart
 *
 * @author wbh
 * @date 2021-05-14
 */
@Configuration
public class JacksonMapperConfig {
    @Autowired(required = false)
    private ObjectMapper objectMapper;

    @Autowired(required = false)
    private JacksonProperties jacksonProperties;

    @PostConstruct
    public void configJackson() {
        if (objectMapper != null && jacksonProperties != null) {
            this.configSerialization(objectMapper, jacksonProperties);
            this.configDeserialization(objectMapper, jacksonProperties);
            this.configOthers(objectMapper, jacksonProperties);
        }
    }

    private void configSerialization(ObjectMapper objectMapper, JacksonProperties properties) {
        Map<SerializationFeature, Boolean> serialization = properties.getSerialization();
        if (serialization != null) {
            serialization.forEach(objectMapper::configure);
        }
    }

    private void configDeserialization(ObjectMapper objectMapper, JacksonProperties properties) {
        Map<DeserializationFeature, Boolean> deserialization = properties.getDeserialization();
        if (deserialization != null) {
            deserialization.forEach(objectMapper::configure);
        }
    }

    private void configOthers(ObjectMapper objectMapper, JacksonProperties properties) {
        if (properties.getDateFormat() != null) {
            objectMapper.setDateFormat(new SimpleDateFormat(properties.getDateFormat()));
        }
        if (properties.getTimeZone() != null) {
            objectMapper.setTimeZone(properties.getTimeZone());
        }
        if (properties.getLocale() != null) {
            objectMapper.setLocale(properties.getLocale());
        }
    }
}