Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson : avoiding exceptions due to unmodeled fields

I have some beans, and they model (explicitly) the core data types in a JSon. However, sometimes the Jsons im reading have extra data in them.

Is there a way to annotate/define a Bean in jackson so that it uses explicit field names for some of the fields (the ones I know of, for example), while cramming the extra fields into a map / list ?

like image 762
jayunit100 Avatar asked Feb 03 '26 04:02

jayunit100


1 Answers

Yes there is, assuming you really do want to retain all the extra/unrecognized parameters, then do something like this:

public class MyBean {
    private String field1;
    private String field2;
    private Integer field3;
    private Map <String, Object> unknownParameters ;

    public MyBean() {
        super();
        unknownParameters = new HashMap<String, Object>(16);
    }

    // Getters & Setters here

    // Handle unknown deserialization parameters
    @JsonAnySetter
    protected void handleUnknown(String key, Object value) {
        unknownParameters.put(key, value);
    }
}

To configure global handling of parameters you can choose to define an implementation of DeserializationProblemHandler and register it globally with the ObjectMapper config.

DeserializationProblemHandler handler = new MyDeserializationProblemHandler();
ObjectMapper.getDeserializationConfig().addHandler(handler);

If you find you really do not care about the unknown parameters, then you can simply turn them off. On a per-class basis with the @JsonIgnoreProperties(ignoreUnknown = true), or globally by configuring ObjectMapper:

objectMapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false)
like image 191
Perception Avatar answered Feb 05 '26 22:02

Perception



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!