springboot~重写json序列化方式

public interface WebMvcConfigurer {

    default void configurePathMatch(PathMatchConfigurer configurer) {

    }

    default void configureContentNegotiation(ContentNegotiationConfigurer configurer) {

    }

    default void configureAsyncSupport(AsyncSupportConfigurer configurer) {

    }

...

}

我们来定义自己的WebMvcConfigurer,并且重写一个JSON输出的格式

@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));

            }

        }

    }

深圳网站建设www.sz886.com

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。