天天看點

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

已經提供了三種,分别是:

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 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;           

本章源碼位址:

https://github.com/hengboy/api-boot/tree/master/api-boot-samples/api-boot-sample-http-converter