简体   繁体   English

使用Jackson将json映射到java对象时聚合所有错误

[英]Aggregate all the errors while mapping json to java object using Jackson

I'm trying to map a JSON string to a Java Object using Jackson ObjectMapper. 我正在尝试使用Jackson ObjectMapper将JSON字符串映射到Java对象。 If there is a mapping error, Jackson throws an exception when it first encounters the error. 如果存在映射错误,Jackson会在第一次遇到错误时抛出异常。 Is there a way to ask the ObjectMapper to map all the field while collecting the errors, and return all possible errors together? 有没有办法要求ObjectMapper在收集错误时映射所有字段,并将所有可能的错误一起返回?

The Java class Java类

public class Test {
    public int field1;
    public int field2;
    public Test() {}
}

Mapper Code snippet 映射器代码片段

String json = "{\"field1\":field, \"field2\":anotherField}";
Test test = new ObjectMapper().readValue(json, Test.class);

The above code fails when it tries to parse 'field' to int, and doesn't check for remaining fields. 上面的代码在尝试将“field”解析为int时失败,并且不检查剩余的字段。 However, the in the code, neither field1 nor field2 can be parsed. 但是,在代码中,field1和field2都不能被解析。 Is there a way to get all the potential errors at once, so I don't have to fix 1 error at a time? 有没有办法立即得到所有潜在的错误,所以我不必一次修复1个错误?

Well, IMHO the problem does not have one simple solution. 那么,恕我直言,这个问题没有一个简单的解决方案。 However particular solutions can be found. 但是可以找到特定的解决方案。

If you want to ignore missing fields just use annotation 如果要忽略缺少的字段,只需使用注释即可

@JsonIgnoreProperties(ignoreUnknown = true)

Supporting unparsable data is more complicated. 支持不可解决的数据更复杂。 Please take a look on correct answer from this discussion enter link description here . 请在此讨论中查看正确答案,请在此处输入链接说明

It however will not help if your JSON is syntactically wrong, for example if coma or colon are missing. 但是,如果你的JSON在语法上是错误的,那将无济于事,例如,如果缺少昏迷或冒号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM