1

我有两个类Aand B,它们都有公共 getter 和构造函数,在构造函数参数上标有@JsonCreator@JsonProperty。当提供正确的 json 时,这两个类都被正确反序列化。但是,当我提供一个作为类类型 A 的投影的 json 并尝试将其反序列化为 B 类型对象时,我希望会引发异常。原来jackson正确地将json反序列化为B型对象,但是这个对象只是null。这是默认行为吗?MyObjectMapper是用new ObjectMapper(). 我可以以任何方式对其进行配置,以便在所描述的情况下引发异常吗?

A类实现:

@JsonIgnoreProperties(ignoreUnknown = true)
final class A {

    private final String propertyA;

    @JsonCreator
    A(@JsonProperty("propertyA") String propertyA) {
        this.propertyA = propertyA;
    }

    public String getPropertyA() {
        return propertyA;
    }

    @Override
    public String toString() {
        return "A{" +
            "propertyA='" + propertyA + '\'' +
            '}';
    }

}

B类实现:

@JsonIgnoreProperties(ignoreUnknown = true)
final class B {

    private final String propertyB;

    @JsonCreator
    B(@JsonProperty("propertyB") String propertyB) {
        this.propertyB = propertyB;
    }

    public String getPropertyB() {
        return propertyB;
    }

    @Override
    public String toString() {
        return "B{" +
            "propertyB='" + propertyB + '\'' +
            '}';
    }

}

具有 B 类投影的 Json:{"propertyB":"propertyBValue"}

反序列化代码:

String jsonWithBObject = "{\"propertyB\":\"propertyBValue\"}";

A deserializedAObject = mapFromJsonToObject(jsonWithBObject, A.class);
private <T> T mapFromJsonToObject(String json, Class<T> targetClass) {
    try {
        return objectMapper.readValue(json, targetClass);
    } catch (JsonProcessingException exception) {
        throw new RuntimeException();
    }
}

运行此代码后,没有抛出异常,并且deserializdAObject包含:A{propertyA='null'}

4

2 回答 2

2

用于@JsonProperty(required = true)强制杰克逊在丢失密钥时抛出异常

仅部分支持此属性。摘自杰克逊 javadoc:

 Note that as of 2.6, this property is only used for Creator
 Properties, to ensure existence of property value in JSON:
 for other properties (ones injected using a setter or mutable
 field), no validation is performed. Support for those cases
 may be added in future.
于 2020-05-24T13:29:43.633 回答
1

@JsonIgnoreProperties(ignoreUnknown = true)导致杰克逊忽略未知属性,反序列化后获得的对象是所有属性都使用默认值初始化的对象(null用于非原始对象)。

用于required=true强制杰克逊在属性丢失的情况下抛出异常。

 @JsonCreator
    B(@JsonProperty(value="propertyB", required=true) String propertyB) {
        this.propertyB = propertyB;
    }
于 2020-05-24T13:14:59.633 回答