0

I'm using jackson-databind-2.9.8.jar.

This is the Java class representation of the model which will contain the deserialized JSON String.

@JsonIgnoreProperties(ignoreUnknown = true)
public class CustomClass {
    @JsonProperty("key-one")
    private String keyOne;
    @JsonProperty("key-two")
    private String keyTwo;
    @JsonProperty("key-three")
    private String keyThree;

    @JsonCreator
    public CustomClass(
        @JsonProperty("key-one") String keyOne,
        @JsonProperty("key-two") String keyTwo,
        @JsonProperty("key-three") String keyThree) {
        this.keyOne = keyOne;
        this.keyTwo = keyTwo;
        this.keyThree = keyThree;
    }
}

The code below then parses json, which contains the JSON structure inside a String.

ObjectMapper mapper = new ObjectMapper().configure(DeserializationFeature.FAIL_ON_MISSING_CREATOR_PROPERTIES, true);

CustomClass customClass;
try {
    customClass = mapper.readValue(json, CustomClass.class);
} catch (IOException e) {
    System.out.println("Parse error");
    e.printStacktrace();
}

The problem is that, if any of the properties:

  • key-one
  • key-two
  • key-three

are missing from the json, an Exception will be thrown.

I would like to only throw an Exception if key-one or key-two is missing, and let key-three be optional.

How can I achieve this?

bobbyrne01
  • 6,295
  • 19
  • 80
  • 150
  • This might help you.https://stackoverflow.com/questions/18320731/jackson-jsonpropertyrequired-true-doesnt-throw-an-exception – Dhruv Kapatel Apr 03 '19 at 18:43

2 Answers2

0

Using the Dhruv Kapatel comment, you should use default (no arg) constructor and your @JsonProperty required should have required = true.

essejoje
  • 175
  • 1
  • 2
  • 8
0

This is how I defined my class to specify which fields are required and which ones are not required:

@JsonIgnoreProperties(ignoreUnknown = true)
public class MyClass {
    @JsonProperty("value-one")
    private String valueOne;
    @JsonProperty("value-two")
    private String valueTwo;
    @JsonProperty("value-three")
    private String valueThree;

    public MyClass(
        @JsonProperty(value = "value-one", required = true) String valueOne,
        @JsonProperty(value = "value-two", required = true) String valueTwo,
        @JsonProperty(value = "value-three", required = false) String valueThree) {
        ..
    }
}
bobbyrne01
  • 6,295
  • 19
  • 80
  • 150