ApiBoot是一款基于SpringBoot1.x,2.x的接口服务集成基础框架, 内部提供了框架的封装集成、使用扩展、自动化完成配置,让接口开发者能够选着性完成开箱即用, 再也不为搭建接口框架而犯愁,从而极大的提升开发效率。java
FastJson
是阿里巴巴提供的一款Json
格式化插件。git
ApiBoot
提供了FastJson
驱动转换接口请求的Json
字符串数据,添加该依赖后会自动格式化时间(格式:YYYY-MM-DD HH:mm:ss)、空对象转换为空字符串返回、空Number转换为0等,还会自动装载ValueFilter
接口的实现类来完成自定义的数据格式转换。github
ApiBoot Http Converter
使用很是简单,只须要在pom.xml
添加以下依赖:spring
<!--ApiBoot Http Converter-->
<dependency>
<groupId>org.minbox.framework</groupId>
<artifactId>api-boot-starter-http-converter</artifactId>
</dependency>
复制代码
ApiBoot
所提供的依赖都不须要添加版本号,具体查看ApiBoot版本依赖json
ApiBoot Http Converter
经过使用SpringBoot
内置的配置参数名来肯定是否开启,在SpringBoot
内能够经过spring.http.converters.preferred-json-mapper
来修改首选的Json
格式化插件,SpringBoot
已经提供了三种,分别是:gson
、jackson
、jsonb
,当咱们配置该参数为fastJson
或不进行配置
就会使用ApiBoot Http Converter
提供的fastJson
来格式化转换Json
返回数据。api
以下所示:app
spring:
http:
converters:
# 不配置默认使用fastJson
preferred-json-mapper: fastJson
复制代码
ValueFilter
是FastJson
的概念,用于自定义转换实现,好比:自定义格式化日期、自动截取小数点等。框架
下面提供一个ValueFilter
的简单示例,具体的使用请参考FastJson
官方文档。ide
在使用ValueFilter
时通常都会搭配一个对应的自定义@Annotation
来进行组合使用,保留自定义小数点位数的示例以下所示:spa
建立 BigDecimalFormatter Annotation
@Target({ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
public @interface BigDecimalFormatter {
/** * 小数位数,默认保留两位 * @return */
int scale() default 2;
}
复制代码
建立 BigDecimal ValueFilter
public class BigDecimalValueFilter implements ValueFilter {
/** * logback */
Logger logger = LoggerFactory.getLogger(BigDecimalValueFilter.class);
/** * @param object 对象 * @param name 对象的字段的名称 * @param value 对象的字段的值 */
@Override
public 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…