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?