Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
247 views
in Technique[技术] by (71.8m points)

java - Collecting unknown properties with Jackson

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"}

And a pojo like this:

@JsonIgnoreProperties(ignoreUnknown = true)
public class A {

    private String a;
    private String b;

    // ...
}

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I don't know of any built-in tool that does this. You can write your own with @JsonAnySetter

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.

Use it like

@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);
}

within the class you're deserializing to, eg. your A class.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...