Jackson - @JsonAnyGetter Example

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

References

Comments