I have a PATCH
REST endpoint, exposing a JSON interface, which can be used to partially update an entity, based on the attributes which are actually sent in the body.
Let's consider a sample class representing the entity:
class Account {
private UUID accountUuid;
private UUID ownerUuid;
private String number;
private String alias;
// constructor, getters and setters omitted
}
where accountUuid
, ownerUuid
and number
are required properties, and alias
is optional. Additionally I have a command class for updating said account:
class UpdateAccountCommand {
private UUID accountUuid;
private String number;
private String alias;
// constructor, getters and setters omitted
}
For my PATCH
endpoint, e.g. PATCH /accounts/{account-uuid}
, I'd like to implement a functionality, that only properties actually sent in the request are changed:
// this should only update the account number
{"number": "123456"}
// this should only update the alias, by setting it to null
{"alias": null}
// this shouldn't update anything
{}
For required properties, this is fairly easy to do. After deserialisation from the JSON string to UpdateAccountCommand
instance using Jackson, I simply check if a required property is null
, and when it's not null
, I update the given property.
However the situation complicates with optional properties, since the alias
property is null
in both cases:
- when the request body explicitly specifies the
alias
as null, - when the
alias
property is not specified in the request body at all.
How can I model these optional properties, so that I can indicate this removable mechanism?