与杰克逊一起收集未知财产 [英] Collecting unknown properties with Jackson
问题描述
我正在使用 Jackson 从 JSON 创建 Java 对象.假设我有一个像这样的 JSON 字符串:
I'm using Jackson for creating Java objects from JSON. Let's suppose I have a JSON string like this:
{"a":"a", "b":"b", "c":"c"}
还有这样的 pojo:
And a pojo like this:
@JsonIgnoreProperties(ignoreUnknown = true)
public class A {
private String a;
private String b;
// ...
}
所以 c 显然是一个未知的属性 - 它将被排除在外.我想知道,有什么办法可以记录 c 是未知的和被忽略的吗?
So c is clearly an unknown property - and it will be left out. I was wondering, is there any way I can log that c was unknown and ignored?
推荐答案
我不知道有任何内置工具可以做到这一点.您可以使用 @JsonAnySetter
I don't know of any built-in tool that does this. You can write your own with @JsonAnySetter
可用于定义非静态的标记注解,双参数方法(属性的第一个参数名称,第二个值设置),用作所有其他情况的后备"处理程序从 JSON 内容中发现无法识别的属性.
Marker annotation that can be used to define a non-static, two-argument method (first argument name of property, second value to set), to be used as a "fallback" handler for all otherwise unrecognized properties found from JSON content.
像这样使用
@JsonAnySetter
public void ignored(String name, Object value) {
// can ignore the 'value' if you only care for the name (though you still need the second parameter)
System.out.println(name + " : " + value);
}
在您要反序列化的类中,例如.你的 A
类.
within the class you're deserializing to, eg. your A
class.
这篇关于与杰克逊一起收集未知财产的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!