在设计 API 时,我定义了一个 UserGeo
模型,该模型包含两个字段 - domain
(字符串数组)和 country
(字符串数组)。
如果没有为 []
提供值,则应在请求正文中使用空列表 domain
。
但是在将 default
属性定义为 []
时,生成的 Spring
代码不会分配空的 ArrayList<> aka []
。
附上代码示例:
招摇定义:
definitions:
UserGeo:
type: "object"
properties:
country:
type: "array"
items:
type: "string"
domain:
type: "array"
items:
type: "string"
default: []
这不会将域值默认为空列表,请检查此生成的 Spring/Java 代码:
.
.
public class Classification {
@JsonProperty("country")
@Valid
private List<String> country = null;
@JsonProperty("domain")
@Valid
private List<String> domain = null;
.
.
当我将域字段定义为 required
时,甚至没有将其定义为默认值,生成的代码会为 domain
分配一个空列表作为默认值。
definitions:
UserGeo:
type: "object"
required:
- "domain"
properties:
country:
type: "array"
items:
type: "string"
domain:
type: "array"
items:
type: "string"
如前所述,生成的代码为域分配了一个空列表。
public class UserGeo {
@JsonProperty("country")
@Valid
private List<String> country = null;
@JsonProperty("domain")
@Valid
private List<String> domain = new ArrayList<String>();
问题是,如果需要一个字段,我想在密钥不可用时将请求标记为 BadRequest,而不是为其分配一个空数组。
谁能告诉我如何让数组使用默认的 []
而不需要?以及如何确保我需要的标记数组项引发 BadRequest 而不是将默认 []
分配给属性?
答案 0 :(得分:0)
我自己也有同样的问题,但更改了逻辑以在数组上使用 minItems 并在数组为空时获取 BadRequest:
definitions:
UserGeo:
type: "object"
required:
- "domain"
properties:
country:
type: "array"
items:
type: "string"
domain:
type: "array"
minItems: 1
items:
type: "string"
HTH