Master Dynamic JSON Fields in Java with @JsonAnyGetter and @JsonAnySetter
This article explains how Jackson's @JsonAnySetter and @JsonAnyGetter annotations let Java classes gracefully handle unknown JSON properties by collecting them into a map during deserialization and emitting them as regular fields during serialization, complete with practical code examples and usage tips.
When a JSON API returns fields that are not known at compile time, Jackson’s @JsonAnySetter and @JsonAnyGetter annotations allow you to collect and serialize these dynamic properties without defining them as explicit class members.
Using @JsonAnySetter
The annotation marks a method that receives unknown JSON fields during deserialization. The method typically stores the key‑value pair in a Map<String, Object>.
@JsonAnySetter
public void addAdditionalProperty(String key, Object value) {
additionalProperties.put(key, value);
}Example JSON with extra fields:
{
"name": "豆瓣酱",
"spicy": true,
"limited_edition": "yes",
"extra_notes": "只在冬天卖"
}Even though the class only defines name and spicy, the fields limited_edition and extra_notes are captured in additionalProperties.
Using @JsonAnyGetter
The annotation marks a method that returns a map of dynamic properties during serialization, causing its entries to be emitted as regular JSON fields.
@JsonAnyGetter
public Map<String, Object> getOtherProps() {
return otherProps;
}Combined usage enables a class to both accept unknown fields when reading JSON and emit them when writing JSON, making it ideal for flexible data structures such as configuration objects, plugin metadata, or any payload where fields may vary.
Full 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;
}
}Serializing an instance with extra properties produces JSON like:
{"name":"John","age":30,"address":"123 Street","nickname":"Johnny"}This approach is especially suitable for JSON structures with non‑fixed fields that may need dynamic extension.
Java Backend Technology
Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!
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.
