java@JsonUnwrapped在未知属性上禁用Jackson的fail
我正在尝试编写一个简单的类,如果JSON输入字符串可以转换为目标JAVA对象,它将验证JSON输入字符串。
如果在输入JSON字符串中找到任何未知字段,验证程序应该失败。
除了我用@JsonUnwrapped
注释A类中的B对象之外,所有这些都可以正常工作,然后对象映射器将默默地忽略未知属性而不会失败
这是我的密码:
A类:
public class A implements Serializable{
protected String id;
protected String name;
protected @JsonUnwrapped B b;
public A(){
}
public A(String id, String name, B b) {
super();
this.id = id;
this.name = name;
this.b = b;
}
//GETTERS/SETTERS
}
B类:
public class B {
protected String innerId;
protected String innerName;
public B(){
}
public B(String innerId, String innerName) {
super();
this.innerId = innerId;
this.innerName= innerName;
}
//GETTERS/SETTERS
}
验证程序类:
public class JsonValidator{
public boolean validate(){
ObjectMapper mapper = new ObjectMapper();
//mapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true);
try {
mapper.enable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
A a = mapper.readValue(
JsonValidatorBean.class.getResourceAsStream("sample.json"),
A.class);
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
要验证的JSON:
{
"id": "aaaa",
"naome": "aaa",
"innerId" : "bbbb",
"innerName" : "bbb"
}
我用的是杰克逊2.1
我希望这段代码在未知属性“naome”上失败,但事实并非如此,它只是被忽略了。
如果我删除@JsonUnwrapped
并使Json适应具有嵌入式对象,则上述代码将如预期的那样失败
有什么想法吗
# 1 楼答案
是的,这是真的。由于需要从父上下文传递展开的属性,因此无法有效地验证哪些属性可以合法地映射到子POJO(正在展开的属性),哪些不可以
有一个RFE试图改进一些东西,以捕获不可映射的属性,但当前版本(2.2之前和包括2.2)不能同时进行展开和防止不可映射的属性