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.class, new StringSerializer())
19 .serializerByType(Long.TYPE, new StringSerializer())
20 .serializerByType(Double.class, new NumberSerializer())
21 .serializerByType(Double.TYPE, new NumberSerializer())
22 .serializerByType(BigDecimal.class, new 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 }