springboot~重寫json序列化方式

在springboot裏,推薦咱們經過WebMvcConfigurer的派生類重寫你的請求,你能夠利用WebMvcConfigurer對http請求添加一些攔截器,addCorsMappings,addResourceHandlers,消息返回格式等等,須要注意的是,你須要使用@EnableWebMvc註解override springboot默認的方法;WebMvcConfigurer雖然是接口,但它的方法都是有default默認實現的。java

public interface WebMvcConfigurer {
    default void configurePathMatch(PathMatchConfigurer configurer) {
    }

    default void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
    }

    default void configureAsyncSupport(AsyncSupportConfigurer configurer) {
    }
...
}

咱們來定義本身的WebMvcConfigurer,而且重寫一個JSON輸出的格式spring

@Configuration
@EnableWebMvc //覆蓋默認的配置
public class WebMvcConfigurerImpl implements WebMvcConfigurer {

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        MappingJackson2HttpMessageConverter jackson2HttpMessageConverter = new MappingJackson2HttpMessageConverter();
        ObjectMapper objectMapper = new ObjectMapper();

        /**
         * 序列換成Json時,將全部的Long變成String
         * 由於js中得數字類型不能包括全部的java Long值
         */
        SimpleModule simpleModule = new SimpleModule();
        simpleModule.addSerializer(Long.class, ToStringSerializer.instance);
        simpleModule.addSerializer(Long.TYPE, ToStringSerializer.instance);

        // 全部的double類型返回保留三位小數
        simpleModule.addSerializer(BigDecimal.class, new MoneySerialize());

        // double保留兩位小數
        simpleModule.addSerializer(Double.class, new DoubleSerialize());
        simpleModule.addSerializer(Double.TYPE, new DoubleSerialize());

        objectMapper.registerModule(simpleModule);
        jackson2HttpMessageConverter.setObjectMapper(objectMapper);
        converters.add(jackson2HttpMessageConverter);
    }
/**
     * money serializer.
     */
    public class MoneySerialize extends JsonSerializer<Object> {
        //修改要除的數據
        final BigDecimal TEMP = BigDecimal.valueOf(1000000L);

        @Override
        public void serialize(Object value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
            if (value != null) {
                BigDecimal bigDecimal = new BigDecimal(value.toString());
                gen.writeNumber(bigDecimal.divide(TEMP, 4, RoundingMode.DOWN));
            }
        }
    }

    /**
     * double serializer.
     */
    public class DoubleSerialize extends JsonSerializer<Double> {

        private DecimalFormat df = new DecimalFormat("##.00");

        @Override
        public void serialize(Double value, JsonGenerator gen, SerializerProvider serializers)
                throws IOException, JsonProcessingException {
            if (value != null) {
                gen.writeString(df.format(value));
            }
        }
    }

而後咱們在返回對象以後,它的double,BigDecimal的屬性將被格式化springboot

{"name":"zzl","email":null,"sex":null,"total":"5.00","totalMoney":0.0001}
相關文章
相關標籤/搜索