Reputation:
I am deserializing a JSON into a model with Jackson. Say I have the following model:
class Model {
private String fieldA;
private Optional<String> fieldB;
}
Here, fieldA
is non-nullable. In the JSON, it can either be absent or filled in:
{
}
or
{
"fieldA": "value"
}
In Java, the not filled in-case results in a null value of the member fieldA
.
My question: is there a way to reject a null value for fieldA
? For the following input JSON, Jackson should throw an exception:
{
"fieldA": null
}
Note that I only want that behaviour for fieldA
, and not fieldB
, since fieldB
is nullable (and hence it is wrapped around an Optional
in the model).
I could also wrap fieldA
in an Optional
and add some bean validation there, but I would rather not change the model.
Upvotes: 2
Views: 1803
Reputation: 4807
No Jackson does not provide validation API. You can just ignore null value by including @JsonInclude(Include.NON_NULL)
to the class or use Bean Validation API which will validate and throw errors if conditions are not satisfied.
UPDATE:
For your comment answer, if anyhow you just wanted to skip fieldA value if it is null and let other allowed them than in setter method you could just manually check.
In your case:
public void setFieldA(String fieldA) {
if (fieldA != null) {
this.fieldA = fieldA;
}
}
Upvotes: 1