I use Jackson to deserialize JSON to an immutable custom Java object. Here is the class:
final class DataPoint {
private final int count;
private final double mean;
@JsonCreator
DataPoint(
@JsonProperty("count") int count,
@JsonProperty("mean") double mean) {
if (count <= 0) {
throw new IllegalArgumentException("...");
}
this.count = count;
this.mean = mean;
}
// getters...
}
Here is the JSON I deserialize:
{
"count": 1,
"mean": 2
}
It works fine. Now I break the JSON, i.e. remove one proprerty:
{
"count": 1
}
The deserialization code is:
String json = "..."; // the second JSON
ObjectMapper mapper = new ObjectMapper();
DataPoint data = mapper.readValue(json, DataPoint.class);
Now I get count == 1, and mean == 0.0. Instead, I would like the Jackson to throw an exception, sine one of the required field is missing in the JSON. How can I archive that?
Thank you a lot, guys!
@JsonProperty("mean") Double meanand check whether it is null or not?