首页 > 解决方案 > BigDecimal 作为 Swagger 防御中的字符串

问题描述

我想在swagger.json 中将BigDecimal定义为 String 的对象

现在我可以做

"MyObject": {
  "type": "object",
  "properties": {
    "amountOfMoney": {
       "type": "string",
       "pattern": "d+([.]d+)?"
    },
    "name": {
      "type": "string"
    }
  },
  "title": "MyObject"
}

另一种方式,我可以将 amountOfMoney 定义为一个数字。

"MyObject": {
  "type": "object",
  "properties": {
    "amountOfMoney": {
      "type": "number"
      "minimum": 0.0,
      "maximum": 100.0,
      "exclusiveMinimum": false,
      "exclusiveMaximum": false
    },
    "name": {
      "type": "string"
    }
  },
  "title": "MyObject"
}

Java 类防御

public class MyObject {

    private BigDecimal amountOfMoney;
    private String name;

    //Getters, setters.
}

我如何执行最小最大验证,就像在第二个示例中一样?

更新

我们使用 springfox 2.8.0。

<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-swagger-ui</artifactId>
    <version>2.8.0</version>
</dependency>
<dependency>
    <groupId>io.springfox</groupId>
    <artifactId>springfox-bean-validators</artifactId>
    <version>2.8.0</version>
</dependency>

我们有配置(作为 Spring bean),我可以在其中添加替代品。

Docket(DocumentationType.SWAGGER_2)
    .select()
    .paths(PathSelectors.any())
    .build()
    .pathMapping("/")
    // see https://stackoverflow.com/a/40737219
    .directModelSubstitute(MyObject .class, String.class)

我什至可以使用替代BigDecimalString!我想为该字符串设置格式,以确保我将获得最小值和最大值之间的数字。

不建议从数字创建 BigDecimal。 另一个链接

https://swagger.io/docs/specification/data-models/data-types/

Spring Pageable 接口的 Swagger 文档

例如,日期有字符串格式。我如何为数字制作一个?

标签: javajsonswaggerbigdecimal

解决方案


推荐阅读