【问题标题】:Custom Data Binding in SpringSpring中的自定义数据绑定
【发布时间】:2022-01-31 11:24:39
【问题描述】:

我这里有个情况。假设,我在@RequestBody 中收到这个 JSON,

{
    "resourceId": "R0001",
    "refs": [
        {
            "username": "infinite-despair",
            "roleType": "3"
        },
        {
            "username": "faith-knight",
            "roleType": "2"
        },
        .
        .
        .

    ]
}

我绑定到 POJO,就像这样。

@PostMapping
public ResponseEntity<SomeModel> addRefs(@RequestBody @Valid ResourceRefRequest req) {...}

现在ResourceRefRequest如下,

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@JsonInclude(JsonInclude.Include.NON_NULL)
public class ResourceRefRequest {

    @NotNull(message = "Resource ID is required")
    private String resourceId;

    @NotEmpty
    private List<@Valid RefReqItem> refs;
}

还有RefReqItem,如下,

@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@ToString
@JsonInclude(JsonInclude.Include.NON_NULL)
public class RefReqItem {

    private String resourceId;

    @NotNull(message = "Username is required")
    private String username;

    @NotNull(message = "Role is required")
    private Integer roleType;
}

一切都很好,正如我所期望的那样。唯一的问题是,refReqItem.resourceIdnull,对于所有refs。我想在refs 中填充refReqItem.resourceId 中的每一个,其中一个位于根目录;即,resourceRefRequest.resourceId。任何想法,我们怎样才能做到这一点?

谢谢。

【问题讨论】:

    标签: java json spring-boot data-binding spring-restcontroller


    【解决方案1】:

    ResourceRefRequest 中,您可以创建一个特殊的设置器供您的 JSON 处理程序使用,在代码中进行您自己的后处理:

        @JsonSetter("refs")
        public void setRefsWithResourceId(List<RefReqItem> refs) {
            this.refs = refs.stream()
                .map(ref -> {
                    ref.setResourceId(resourceId);
                    return ref;
                })
                .collect(Collectors.toList());
        }
    

    从 JSON 创建 Java 对象时,将调用此 setter,因为该方法具有 setter 的签名并带有 @JsonProperty("refs") 注释。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-03-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-12-14
      • 2010-10-11
      • 1970-01-01
      相关资源
      最近更新 更多