我正在尝试编写一个简单的类,如果可以将JSON输入字符串转换为目标JAVA对象,它将验证它。如果在输入JSON字符串中找到任何未知字段,验证器应该会失败。它都按预期工作,除非我用@JsonUncel
在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 适应具有嵌入对象,则上述代码将按预期失败。
有什么想法吗?
是的,这是真实的说法。由于从父上下文传递解包的属性需要逻辑,因此无法有效地验证哪些属性可以合法地映射到子 POJO(被解包的属性),哪些不是。
有一个RFE试图改进事物,以捕获不可映射的属性,但当前版本(包括2.2)不能同时进行展开和防止不可映射的属性。