JacksonMapperConfig.java 1.84 KB
package com.glsx.admin.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 init() {
        if (objectMapper != null && jacksonProperties != null) {
            this.configSerialization(objectMapper, jacksonProperties.getSerialization());
            this.configDeserialization(objectMapper, jacksonProperties.getDeserialization());
            this.configOthers(objectMapper, jacksonProperties);
        }
    }

    private void configSerialization(ObjectMapper objectMapper,
            Map<SerializationFeature, Boolean> features) {
        features.forEach(objectMapper::configure);
    }

    private void configDeserialization(ObjectMapper objectMapper,
            Map<DeserializationFeature, Boolean> features) {
        features.forEach(objectMapper::configure);
    }

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