使用 jackson databind 允许在反序列化字符串时特定字段是可选的,而其他字段是必需的

Using jackson databind allow specific field to be optional when deserializing string and others to be required

我正在使用 jackson-databind-2.9.8.jar

这是模型的 Java class 表示,它将包含反序列化的 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;
    }
}

下面的代码然后解析 json,它在 String.

中包含 JSON 结构
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();
}

问题是,如果有任何属性:

json 中缺失,将抛出一个 Exception

如果缺少 key-onekey-two,我只想抛出一个 Exception,并让 key-three 是可选的。

我怎样才能做到这一点?

使用 Dhruv Kapatel 注释,您应该使用默认(无参数)构造函数并且您需要的 @JsonProperty 应该具有 required = true

这就是我定义 class 以指定哪些字段是必需的,哪些不是必需的:

@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) {
        ..
    }
}