ApiBoot - ApiBoot Http Converter 使用文档

时间:2022-06-19
本文章向大家介绍ApiBoot - ApiBoot Http Converter 使用文档,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

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已经提供了三种,分别是:gsonjacksonjsonb,当我们配置该参数为fastJson不进行配置就会使用ApiBoot Http Converter提供的fastJson来格式化转换Json返回数据。

如下所示:

spring:
  http:
    converters:
      # 不配置默认使用fastJson
      preferred-json-mapper: fastJson

自定义ValueFilter

ValueFilterFastJson的概念,用于自定义转换实现,比如:自定义格式化日期、自动截取小数点等。

下面提供一个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 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;