I use Jackson
to deserialize a JSON to an immutable custom Java object. Here is the class:
final class DataPoint {
private final int count;
private final int lower;
private final int median;
private final int upper;
@JsonCreator
DataPoint(
@JsonProperty("count") int count,
@JsonProperty("lower") int lower,
@JsonProperty("median") int median,
@JsonProperty("upper") int upper) {
if (count <= 0) {
throw new IllegalArgumentException("...");
}
this.count = count;
this.lower = lower;
this.median = median;
this.upper = upper;
}
// getters...
}
Here is the JSON I deserialize:
{
"count": 3,
"lower": 2,
"median": 3,
"upper": 4
}
It works fine. Now I break the JSON, i.e. douplicate the lower
property:
{
"count": 4,
"lower": 2,
"lower": 3,
"median": 4,
"upper": 5
}
Now I get count == 4
, and lower == 3
. Instead, I would like the Jackson
to fail deserilizing, since there is a duplicate property in the JSON (lower
).
Here is the deserializing code:
String json = "..."; // the second JSON
ObjectMapper mapper = new ObjectMapper().enable(
DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES,
DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES,
DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY)
.disable(DeserializationFeature.ACCEPT_FLOAT_AS_INT);
DataPoint data = mapper.readValue(json, DataPoint.class);
Folks, can I make the Jackson
to fail when desierializing a JSON with duplicate property keys?
Thank you a lot, guys!