Skip to content
Advertisement

Custom Data Binding in Spring

I have a situation here. Suppose, I’m receiving this JSON in the @RequestBody,

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

    ]
}

Which I’m binding to a POJO, like so.

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

Now, ResourceRefRequest, is as follows,

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

and, RefReqItem, is as follows,

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

Things are pretty well, as I expect them to be. The only problem is, refReqItem.resourceId is null, for all refs. I want to populate each of, refReqItem.resourceId, in the refs, with the one at the root; namely, with, resourceRefRequest.resourceId. Any idea, how can we achieve this?

Thanks.

Advertisement

Answer

In ResourceRefRequest, you can create a special setter for your JSON handler to use, to do your own post-processing in code:

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

When creating the Java object from JSON, this setter will be called because the method has the signature of a setter and is annotated with @JsonProperty("refs").

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement