danissimo :
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!
Darshan Mehta :
You can enable STRICT_DUPLICATE_DETECTION
to make the parser throw an Exception
if there's a duplicate property, e.g.:
String s = "{\"count\": 4,\"lower\": 2,\"lower\": 3,\"median\": 4,\"upper\": 5}";
ObjectMapper mapper = new ObjectMapper();
mapper.enable(JsonParser.Feature.STRICT_DUPLICATE_DETECTION);
JsonNode readTree = mapper.readTree(s);
System.out.println(readTree.toString());
This will throw the following exception:
Exception in thread "main" com.fasterxml.jackson.core.JsonParseException: Duplicate field 'lower'
Here's the documentation.
Guess you like
Origin http://10.200.1.11:23101/article/api/json?id=467699&siteId=1