Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON Patch Request validation in Java

In my spring boot service, I'm using https://github.com/java-json-tools/json-patch for handling PATCH requests.

Everything seems to be ok except a way to avoid modifying immutable fields like object id's, creation_time etc. I have found a similar question on Github https://github.com/java-json-tools/json-patch/issues/21 for which I could not find the right example.

This blog seems to give some interesting solutions about validating JSON patch requests with a solution in node.js. Would be good to know if something similar in JAVA is already there.

like image 372
shoaib1992 Avatar asked May 01 '18 22:05

shoaib1992


1 Answers

Under many circumstances you can just patch an intermediate object which only has fields that the user can write to. After that you could quite easily map the intermediate object to your entity, using some object mapper or just manually.

The downside of this is that if you have a requirement that fields must be explicitly nullable, you won’t know if the patch object set a field to null explicitly or if it was never present in the patch.

What you can do too is abuse Optionals for this, e.g.

public class ProjectPatchDTO {

    private Optional<@NotBlank String> name;
    private Optional<String> description;
}

Although Optionals were not intended to be used like this, it's the most straightforward way to implement patch operations while maintaining a typed input. When the optional field is null, it was never passed from the client. When the optional is not present, that means the client has set the value to null.

like image 155
Sebastiaan van den Broek Avatar answered Sep 29 '22 02:09

Sebastiaan van den Broek