Master Dynamic JSON Fields in Java with @JsonAnyGetter and @JsonAnySetter
This article explains how to handle unknown or dynamic JSON properties in Java using Jackson's @JsonAnySetter to collect them into a map and @JsonAnyGetter to serialize them back, complete with practical code examples and output demonstrations.
Using @JsonAnySetter and @JsonAnyGetter for Dynamic JSON Properties
When a JSON response contains fields that are not known at compile time, Jackson provides the annotations @JsonAnySetter and @JsonAnyGetter to collect and serialize these dynamic properties.
How @JsonAnySetter works
Annotate a method that receives a key and value; Jackson calls it for each unknown property, storing them in a Map<String, Object>.
@JsonAnySetter
public void addAdditionalProperty(String key, Object value) {
additionalProperties.put(key, value);
}How @JsonAnyGetter works
Annotate a method that returns the map of dynamic properties; during serialization Jackson merges the map entries into the JSON output.
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return additionalProperties;
}Complete Example
public class Person {
private String name;
private int age;
private Map<String, Object> additionalProperties = new HashMap<>();
// getters and setters omitted
@JsonAnySetter
public void addAdditionalProperty(String key, Object value) {
additionalProperties.put(key, value);
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return additionalProperties;
}
}Deserialization example:
String json = "{\"name\":\"John\",\"age\":30,\"address\":\"123 Street\",\"nickname\":\"Johnny\"}";
ObjectMapper mapper = new ObjectMapper();
Person person = mapper.readValue(json, Person.class);Serialization produces:
{"name":"John","age":30,"address":"123 Street","nickname":"Johnny"}This approach is suitable for JSON structures with unpredictable fields such as configuration items, plugin metadata, or extensible APIs.
Architecture Digest
Focusing on Java backend development, covering application architecture from top-tier internet companies (high availability, high performance, high stability), big data, machine learning, Java architecture, and other popular fields.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
