posts - 3, comments - 0, trackbacks - 0, articles - 1

springboot jackson全局配置

Posted on 2021-09-08 13:46 whitesky 阅读(884) 评论(0)  编辑  收藏
springboot:2.3.5.RELEASE

 1 @Configuration
 2 public class JsonConfig {
 3 
 4     @Bean
 5     public NumberFormatCustomizer getNumberFormatCustomizer() {
 6         // 配置jackson全局浮点数格式化输出
 7         return new NumberFormatCustomizer();
 8     }
 9 
10     static class NumberFormatCustomizer implements Jackson2ObjectMapperBuilderCustomizer {
11 
12         @Override
13         public void customize(Jackson2ObjectMapperBuilder jacksonObjectMapperBuilder) {
14             // 配置json序列化
15             // long类型输出字符串
16             // double和BigDecimal保留两位小数截断输出字符串
17             jacksonObjectMapperBuilder
18                     .serializerByType(Long.classnew StringSerializer())
19                     .serializerByType(Long.TYPE, new StringSerializer())
20                     .serializerByType(Double.classnew NumberSerializer())
21                     .serializerByType(Double.TYPE, new NumberSerializer())
22                     .serializerByType(BigDecimal.classnew NumberSerializer());
23         }
24     }
25 
26     public static class NumberSerializer extends JsonSerializer<Number> {
27 
28         private NumberFormat numberFormat;
29         public NumberSerializer() {
30             this.numberFormat = NumberFormat.getInstance();
31             // 最多两位小数
32             this.numberFormat.setMaximumFractionDigits(2);
33             // 截断
34             this.numberFormat.setRoundingMode(RoundingMode.FLOOR);
35         }
36 
37         @Override
38         public void serialize(Number value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
39             if (value != null) {
40                 gen.writeString(this.numberFormat.format(value));
41             }
42         }
43     }
44 }


只有注册用户登录后才能发表评论。


网站导航: