Configure the Jackson library for dynamic attributes

Asked

Viewed 527 times

2

I am 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 (average_exclusive_time). It may have another name according to a parameter passed in the request of a web service.

Is there any way to set up the Jackson library for it to mask this last dynamic value for a field called value or maybe to a Map.

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

1 answer

2


You can use the annotation @JsonAnySetter in a kind if Setter special 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 does not find will be forwarded to the Setter special.

Use this annotation in conjunction with @JsonAnyGetter so that the map is also included in the serialization of the bean to Json.

See an example of implementation below:

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);
}
  • 1

    This solution has worked. I noticed that if I create the setters of the other attributes, it will only enter @Jsonanysetter for the attributes that do not have Setter.

  • @Renatodinhaniconceição That’s right. I improved the answer to try to make it clearer.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.