Reputation: 341
I am mapping my API JSON response to Java object using ObjectMapper (Jackson). Below is how my json looks like :
[
{
firstKey : "value1",
secondKey : "value2",
thirdKey : "value3"
},
{
firstKey : "value4",
secondKey : "value5",
thirdKey : "value6"
}
]
Required fields are : firstKey secondKey thirdKey
Some of my JSON responses might not have all these three required fields, for which I would like Jackson to throw exception while deserializing. How should I let Jackson know about the required fields ? Is there any annotation for it, except JsonProperty(required = true) since this does not works ?
Also, if a key has null value, it is accepted default value, so I cannot use @NotNull as well. For eg : [ { firstKey : null, secondKey : "value2", thirKey : "value3" } ] Above is valid JSON and should parsed without any exception during deserialization.
Upvotes: 1
Views: 12082
Reputation: 12215
Validation functionality overall is not implemented in Jackson since it is considered to be out of scope, see for example Jackson - Required property?.
And some information about why the annotation @JsonProperty(required = true)
does not work on field can be found here: Jackson @JsonProperty(required=true) doesn't throw an exception.
However there is a trick that might work for null
& existing well-valued fields values but throw an exception if the field is missing completely. Create a constructor with annotation @JsonCreator
(and do not create a default constructor!) where the same annotation @JsonProperty(value = "*field_name*", required = true)
is used and it will throw in case of missing field, so like:
@Getter @Setter
public class KeyHolder {
private String firstKey;
private String secondKey;
private String thirdKey;
@JsonCreator
public KeyHolder(
@JsonProperty(value = "firstKey", required = true) String firstKey,
@JsonProperty(value = "secondKey", required = true) String secondKey,
@JsonProperty(value = "thirdKey", required = true) String thirdKey) {
this.firstKey = firstKey;
this.secondKey = secondKey;
this.thirdKey = thirdKey;
}
}
With these, doing:
new ObjectMapper().readValue("{ \"firstKey\": \"val1\", \"secondKey\": \"val2\" }"
, KeyHolder.class);
should result into something like:
com.fasterxml.jackson.databind.exc.MismatchedInputException: Missing required creator property 'thirdKey' (index 2)
Any required parameter needs also to be a constructor parameter. So if there is added field fourthKey
the constructor needs also a fix so like adding:
@JsonProperty(value = "fourthKey", required = true) String fourthKey) {
and
this.fourthKey = fourthKey;
Upvotes: 2