Configuring the Jackson Library for Dynamic Attributes

2

I'm using the Jackson library to transform the following JSON into a Java object.

{"name":"Agent/MetricsReported/count","begin":"2014-02-04T09:44:00Z","end":"2014-02-04T09:45:00Z","app":"","agent_id":, "average_exclusive_time":0.23999999463558197}

My problem is that all JSON fields are fixed, except the last one ( average_exclusive_time ). It can have another name according to a parameter passed in the request of a web service.

Is there a way to configure the Jackson library to map this last dynamic value to a field called value or perhaps to Map .

What I want to avoid is having to create a class for every possible variation of this last field that can take other names.

    
asked by anonymous 04.02.2014 / 13:10

1 answer

2

You can use the annotation @JsonAnySetter in a type if setter associated with a Map .

According to the documentation itself, the method with this annotation will serve as a fallback when an attribute does not exist in the bean , that is, the existing attributes will be filled normally and only those that Jackson will not find will be forwarded to the special setter.

Use this annotation together with @JsonAnyGetter so that the map is also included in the bean serialization for Json.

See an example of the following implementation:

private Map<String,Object> values = new HashMap<String,Object>();

@JsonAnyGetter
public Map<String,Object> values() {
    return values;
}

@JsonAnySetter
public void set(String key, Object value) {
    values.put(key, value);
}
    
04.02.2014 / 13:35