Spring 嵌套的注释验证和索引 objects

Spring annotation validation and indexing for nested objects

在 Spring MVC 中,我用 bean-validation 注释注释了我的 parent Dto 和 child Dto 列表:

class ParentDto {
  @NotBlank
  private String parentName;
  @Valid
  private Set<ChildDto> childList;
  //getter and setter
}

class ChildDto {
  @NotBlank
  private String childName;
  //getter and setter
}

如果 childName 在 child object 之一中为空,则 spring returns 错误消息如下,没有索引 child object:

[{"errorCode":"NotNull","field":"parentDto.childList[].childDto ","message":"may not be null"}]

如何启用 spring 到 return 带有索引的消息(告诉 child 有问题)如下所示:

[{"errorCode":"NotNull","field":"parentDto.childList[1].childDto ","message":"may not be null"}]

我弄清楚了错误消息中缺少索引的原因。由于我使用 Set 而不是 List 来收集子对象,因此它无法对其进行索引。一旦更改为列表,它就可以正常工作。