Jackson - @JsonAnySetter Example

In this article, we will discuss how to use Jackson  @JsonAnySetter annotation 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 @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

References

Comments