ApiBoot是一款基于SpringBoot1.x,2.x的接口服务集成基础框架, 内部提供了框架的封装集成、使用扩展、自动化完成配置,让接口开发者可以选着性完成开箱即用, 不再为搭建接口框架而犯愁,从而极大的提高开发效率。
FastJson
是阿里巴巴提供的一款Json
格式化插件。
ApiBoot
提供了FastJson
驱动转换接口请求的Json
字符串数据,添加该依赖后会自动格式化时间(格式:YYYY-MM-DD HH:mm:ss)、空对象转换为空字符串返回、空Number转换为0等,还会自动装载ValueFilter
接口的实现类来完成自定义的数据格式转换。
引入Http Converter
ApiBoot Http Converter
使用非常简单,只需要在pom.xml
添加如下依赖:
<!--ApiBoot Http Converter-->
<dependency><groupId>org.minbox.framework</groupId><artifactId>api-boot-starter-http-converter</artifactId>
</dependency>
复制代码
ApiBoot
所提供的依赖都不需要添加版本号,具体查看ApiBoot版本依赖
相关配置
ApiBoot Http Converter
通过使用SpringBoot
内置的配置参数名来确定是否开启,在SpringBoot
内可以通过spring.http.converters.preferred-json-mapper
来修改首选的Json
格式化插件,SpringBoot
已经提供了三种,分别是:gson
、jackson
、jsonb
,当我们配置该参数为fastJson
或不进行配置
就会使用ApiBoot Http Converter
提供的fastJson
来格式化转换Json
返回数据。
如下所示:
spring:
http:
converters:# 不配置默认使用fastJson
preferred-json-mapper: fastJson复制代码
自定义ValueFilter
ValueFilter
是FastJson
的概念,用于自定义转换实现,比如:自定义格式化日期、自动截取小数点等。
下面提供一个ValueFilter
的简单示例,具体的使用请参考FastJson
官方文档。
ValueFilter示例
在使用ValueFilter
时一般都会搭配一个对应的自定义@Annotation
来进行组合使用,保留自定义小数点位数的示例如下所示:
创建 BigDecimalFormatter Annotation
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface BigDecimalFormatter {/*** 小数位数,默认保留两位* @return*/int scale() default 2;
}
复制代码
创建 BigDecimal ValueFilter
public class BigDecimalValueFilterimplements ValueFilter {/*** logback*/Logger logger = LoggerFactory.getLogger(BigDecimalValueFilter.class);/*** @param object 对象* @param name 对象的字段的名称* @param value 对象的字段的值*/@Overridepublic Object process(Object object, String name, Object value) {if (ValidateTools.isEmpty(value) || !(value instanceof BigDecimal)) {return value;}return convertValue(object, name, value);}/*** 转换值** @param object 字段所属对象实例* @param name 字段名称* @param value 字段的值* @return*/Object convertValue(Object object, String name, Object value) {try {/*** 反射获取field*/Field field = object.getClass().getDeclaredField(name);/***判断字段是否存在@BigDecimalFormatter注解*/if (field.isAnnotationPresent(BigDecimalFormatter.class)) {BigDecimalFormatter bigDecimalFormatter = field.getAnnotation(BigDecimalFormatter.class);// 执行格式化BigDecimal decimal = (BigDecimal) value;System.out.println(bigDecimalFormatter.scale());// 保留小数位数,删除多余value = decimal.setScale(bigDecimalFormatter.scale(), BigDecimal.ROUND_DOWN).doubleValue();}} catch (Exception e) {logger.error("格式化BigDecimal字段出现异常:{}", e.getMessage());}return value;}
}
复制代码
使用 BigDecimalFormatter Annotation
@BigDecimalFormatter
private BigDecimal decimalValue;
复制代码
本章源码地址:github.com/hengboy/api…