jayunit100
jayunit100

Reputation: 17648

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 ?

Upvotes: 3

Views: 2990

Answers (1)

Perception
Perception

Reputation: 80603

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)

Upvotes: 10

Related Questions