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.

Architecture Digest
Architecture Digest
Architecture Digest
Master Dynamic JSON Fields in Java with @JsonAnyGetter and @JsonAnySetter

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.

Dynamic JSON properties illustration
Dynamic JSON properties illustration
DynamicProperties
Architecture Digest
Written by

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.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.