简体   繁体   中英

JSON -> Immutable custom Java object. Insufficient data in JSON

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, ie 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!

Since you're using a constructor, you can enable DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES to throw an exception on missing properties:

String json = "..."; // the second JSON
ObjectMapper mapper = new ObjectMapper()
        .enable(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES);
DataPoint data  = mapper.readValue(json, DataPoint.class);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM