Jackson @JsonAnyGetter and @JsonAnySetter Example

In this article, we will discuss how to use Jackson @JsonAnyGetter and @JsonAnySetter annotations with examples.


We use the ObjectMapper class which provides the functionality for reading and writing JSON, either to or from basic  POJOs.
Before getting started, let's define the required Jackson API dependencies.

1. Dependencies

Let’s first add the following dependencies to the pom.xml:
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version>
</dependency>
This dependency will also transitively add the following libraries to the classpath:
  • jackson-annotations-2.9.8.jar
  • jackson-core-2.9.8.jar
  • jackson-databind-2.9.8.jar
Always use the latest versions on the Maven central repository for Jackson databind.

2. Jackson @JsonAnyGetter

The @JsonAnyGetter annotation allows the flexibility of using a Map field as standard properties.
From Javadoc - @JsonAnyGetter is a marker annotation that can be used to define a non-static,no-argument method to be an "any getter"; accessor for getting a set of key/value pairs, to be serialized as part of containing POJO(similar to unwrapping) along with regular property values it has.
As with JsonAnySetter, only one property should be annotated with this annotation; if multiple methods are annotated, an exception may be thrown.

Jackson @JsonAnyGetter Example

Here's a quick example – the SampleJavaBean entity has the name property and a set of extendable attributes in the form of key/value pairs:
package net.javaguides.jackson.JsonAnyGetter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.databind.ObjectMapper;

public class SampleJavaBean {
    public String name;
    private Map < String, String > properties;

    public SampleJavaBean() {
        properties = new HashMap < String, String > ();
    }

    public SampleJavaBean(final String name) {
        this.name = name;
        properties = new HashMap < String, String > ();
    }

    @JsonAnyGetter
    public Map < String, String > getProperties() {
        return properties;
    }

    public static void main(String[] args) throws IOException {

        SampleJavaBean bean = new SampleJavaBean("SampleJavaBean");
        bean.getProperties().put("key1", "val1");
        bean.getProperties().put("key2", "val2");

        // convert object to json
        String result = new ObjectMapper().writeValueAsString(bean);
        System.out.println(result);
    }
}
When we serialize an instance of this entity, we get all the key-values in the Map as standard, plain properties:
{"name":"SampleJavaBean","key1":"val1","key2":"val2"}

3. Jackson @JsonAnySetter

@JsonAnySetter allows us the flexibility of using a Map as standard properties. On deserialization, the properties from JSON will simply be added to the map.
From Javadoc -@JsonAnySetter is a marker annotation that can be used to define a logical "any setter" mutator --either using non-static, two-argument method (first argument name of property, second value to set) or a field (of type java.util.Map or POJO) - to be used as a "fallback" handler for all otherwise unrecognized properties found from JSON content.

Jackson @JsonAnySetter Example

Let's use @JsonAnySetter to deserialize the entity SampleJavaBean:
package net.javaguides.jackson.JsonAnyGetter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.databind.ObjectMapper;

public class SampleJavaBean {
    public String name;
    private Map < String, String > properties;

    public SampleJavaBean() {
        properties = new HashMap < String, String > ();
    }

    public SampleJavaBean(final String name) {
        this.name = name;
        properties = new HashMap < String, String > ();
    }

    @JsonAnySetter
    public void add(final String key, final String value) {
        properties.put(key, value);
    }

    @JsonAnyGetter
    public Map < String, String > getProperties() {
        return properties;
    }

    public static void main(String[] args) throws IOException {

        String json = "{\"name\":\"SampleJavaBean\",\"key1\":\"val1\",\"key2\":\"val2\"}";
        // convert json to object
        ObjectMapper mapper = new ObjectMapper();
        SampleJavaBean sampleJavaBean = mapper.readValue(json, SampleJavaBean.class);
        Map < String, String > details = sampleJavaBean.getProperties();
        for (String key: details.keySet()) {
            System.out.println(key + ": " + details.get(key));
        }
    }
}
This is the JSON we need to deserialize:
key1: val1
key2: val2

4. Complete Example

package net.javaguides.jackson.JsonAnyGetter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.databind.ObjectMapper;

public class SampleJavaBean {
    public String name;
    private Map < String, String > properties;

    public SampleJavaBean() {
        properties = new HashMap < String, String > ();
    }

    public SampleJavaBean(final String name) {
        this.name = name;
        properties = new HashMap < String, String > ();
    }

    @JsonAnySetter
    public void add(final String key, final String value) {
        properties.put(key, value);
    }

    @JsonAnyGetter
    public Map < String, String > getProperties() {
        return properties;
    }

    public static void main(String[] args) throws IOException {

        String json = "{\"name\":\"SampleJavaBean\",\"key1\":\"val1\",\"key2\":\"val2\"}";

        SampleJavaBean bean = new SampleJavaBean("SampleJavaBean");
        bean.add("key1", "val1");
        bean.add("key2", "val2");

        // convert object to json
        String result = new ObjectMapper().writeValueAsString(bean);
        System.out.println(result);

        // convert json to object
        ObjectMapper mapper = new ObjectMapper();
        SampleJavaBean sampleJavaBean = mapper.readValue(json, SampleJavaBean.class);
        Map < String, String > details = sampleJavaBean.getProperties();
        for (String key: details.keySet()) {
            System.out.println(key + ": " + details.get(key));
        }
    }
}
Output:
{"name":"SampleJavaBean","key1":"val1","key2":"val2"}
key1: val1
key2: val2

Free Spring Boot Tutorial | Full In-depth Course | Learn Spring Boot in 10 Hours


Watch this course on YouTube at Spring Boot Tutorial | Fee 10 Hours Full Course

Comments