我有两个类A
and 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'}