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 best‑practice tips.
When a JSON API returns fields that are not known at compile time, you cannot define static Java properties for them. Jackson provides two annotations, @JsonAnySetter and @JsonAnyGetter, to gracefully handle such dynamic attributes.
Using @JsonAnySetter
The annotation marks a method that receives any JSON property not mapped to a regular field. The method typically stores the key‑value pair in a Map<String, Object> (often called additionalProperties).
public void addAdditionalProperty(String key, Object value) {
additionalProperties.put(key, value);
}Example JSON:
{
"name": "豆瓣酱",
"spicy": true,
"limited_edition": "yes",
"extra_notes": "只在冬天卖"
}Even though the Java class only defines name and spicy, the unknown fields limited_edition and extra_notes are automatically added to the map.
Using @JsonAnyGetter
The annotation marks a method that returns a Map containing dynamic properties. During serialization, Jackson flattens this map into regular JSON fields.
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return additionalProperties;
}Combined usage example:
public class Person {
private String name;
private int age;
private Map<String, Object> additionalProperties = new HashMap<>();
@JsonAnySetter
public void addAdditionalProperty(String key, Object value) {
additionalProperties.put(key, value);
}
@JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return additionalProperties;
}
}
public class Main {
public static void main(String[] args) throws Exception {
String json = "{\"name\":\"John\",\"age\":30,\"address\":\"123 Street\",\"nickname\":\"Johnny\"}";
ObjectMapper mapper = new ObjectMapper();
Person person = mapper.readValue(json, Person.class);
System.out.println(mapper.writeValueAsString(person));
}
}The output is
{"name":"John","age":30,"address":"123 Street","nickname":"Johnny"}, showing that both static and dynamic fields are serialized together.
Key Takeaways
Use @JsonAnySetter to collect unknown JSON properties into a map during deserialization.
Use @JsonAnyGetter to expose the map’s entries as regular JSON fields during serialization.
This approach is ideal for flexible data structures such as configuration objects, plugin metadata, or any API where fields may vary.
Java Tech Enthusiast
Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!
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.
