0

whitesky's blogjava

 3 years ago
source link: http://www.blogjava.net/zhangriwang/archive/2021/09/08/435969.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client
posts - 3, comments - 0, trackbacks - 0, articles - 1

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 }

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK