1

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!

5
  • 3
    What if you change to @JsonProperty("mean") Double mean and check whether it is null or not? Commented May 5, 2017 at 8:04
  • @StanislavL: Well, it's a kind of a solution. Than you a lot! Am I right there is no means in Jackson letting me to get what I want witout boxing? Commented May 5, 2017 at 8:12
  • 1
    @StanislavL You won't be able to tell if it's missing, or present but set to null. Commented May 5, 2017 at 8:15
  • 1
    @shmosel it fails on null anyway. It's not possible to convert null to double but your answer is better +1. I suggested just a workaround. Commented May 5, 2017 at 8:17
  • 1
    @StanislavL It's possible that the implicit conversion from null to 0 is acceptable, as long as the property is defined. Your solution would throw an exception in either case. Of course, only OP can say if that's a problem. Commented May 5, 2017 at 8:22

1 Answer 1

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you a lot! You suggestion just works fine. I jsut needed to increate the version of the Jersey BOM. Thankx again, dude!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.