$show=/label

Jackson API @JsonAnyGetter Annotation - Map Example

SHARE:

A quick guide to use @JsonAnyGetter Annotation from Jackson API. @JsonAnyGetter example to parse and serialize the addition map key-value pair as normal properties.

1. Introduction


In this Jackson Annotation Series, You'll be learning @JsonAnyGetter annotation and example program to demonstrate @JsonAnyGetter annotation with Map Example in Jackson API.

Jackson API is mainly integrated with Java tech stack.

Mainly @JsonAnyGetter is used on Map<String, String> property which holds the additional properties which are apart from the normal properties.

Please note that @ JsonAnyGetter is a method level annotation and can not be used on the filed level. If you use so on field level will cause a compile-time error.

This is the first annotation in our series.


Jackson API @JsonAnyGetter Annotation - Map Example



Jackson API @JsonAnyGetter


First, let us see the example program without using @JsonAnyGetter annotation and observer the output.

Furthermore, We will see the how-to flat the key-value pairs of the map as normal values.

Do not worry much about @JsonAnyGetter annotation because after seeing the examples on this, you will be in a good position to use this annotation in your application.

Add the maven dependency before using jackson annotations.

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.11.0</version>
</dependency>

2. Java Example Without @JsonAnyGetter Annotation


First, let us see a simple example of how the map fields are shown in the JSON string format.

Table Class:

package com.javaprogramto.jackson.annotations;

import java.util.HashMap;
import java.util.Map;

public class Table {

    private int id;
    private String modelName;

    private Map<String, String> otherProperties = new HashMap<>();

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getModelName() {
        return modelName;
    }

    public void setModelName(String modelName) {
        this.modelName = modelName;
    }

    public Map<String, String> getOtherProperties() {
        return otherProperties;
    }

    public void setOtherProperties(Map<String, String> otherProperties) {
        this.otherProperties = otherProperties;
    }
}

JsonAnyGetterExample

It is good to understand before using JsonAnyGetter annotation on any getter method.

package com.javaprogramto.jackson.annotations;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.HashMap;
import java.util.Map;

public class JsonAnyGetterExample {

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

        Table table = getTable();

        ObjectMapper mapper = new ObjectMapper();
        String tableAsJson = mapper
                .writerWithDefaultPrettyPrinter()
                .writeValueAsString(table);
        System.out.println("Table as json : "+tableAsJson);


    }

    private static Table getTable() {

        Table table = new Table();

        table.setId(100);
        table.setModelName("Laptop Table");

        Map<String, String> otherProperties = new HashMap<>();

        otherProperties.put("NoOfLegs", "4");
        otherProperties.put("PreferredColor", "White");

        table.setOtherProperties(otherProperties);

        return table;
    }

}

Output:

Table as json : {

  "id" : 100,

  "modelName" : "Laptop Table",

  "otherProperties" : {

    "NoOfLegs" : "4",

    "PreferredColor" : "White"

  }

}

3. Jackson Map Example @JsonAnyGetter Annotation


If you look at generated JSON content it has treated the map properties as separate fields under "otherProperties".

But whenever we added the properties are actually direct properties of the Table. If we can get all of the map fields directly it looks like one entity.

Use JsonAnyGetter annotation on the map getter method so that it can do flat the map fields.

Let us change the Table class and run the main method.

Table class:

@JsonAnyGetter

public Map<String, String> getOtherProperties() {
    return otherProperties;
}
public void setOtherProperties(Map<String, String> otherProperties) {
    this.otherProperties = otherProperties;
}

Next, Run the same main program which we have implemented in the above section, and that produces the following output.

Table as json : {

  "id" : 100,

  "modelName" : "Laptop Table",

  "NoOfLegs" : "4",

  "PreferredColor" : "White"

}

Finally, We have put together the other properties directly under the root table element and removed the "otherProperties" attribute from the JSON content.

4. Using @JsonAnyGetter on Multiple Getters


If you try to use @JsonAnyGetter annotation on multiple getters then it will throw runtime exception "JsonMappingException - Multiple 'any-getters' defined"

@JsonAnyGetter
public String getModelName() {
    return modelName;
}

public void setModelName(String modelName) {
    this.modelName = modelName;
}

@JsonAnyGetter
public Map<String, String> getOtherProperties() {
    return otherProperties;
}


Exception in thread "main" com.fasterxml.jackson.databind.JsonMappingException: Problem with definition of [AnnotedClass com.javaprogramto.jackson.annotations.Table]: Multiple 'any-getters' defined ([method com.javaprogramto.jackson.annotations.Table#getModelName(0 params)] vs [method com.javaprogramto.jackson.annotations.Table#getOtherProperties(0 params)])

 at com.fasterxml.jackson.databind.JsonMappingException.from(JsonMappingException.java:295)

 at com.fasterxml.jackson.databind.SerializerProvider.reportMappingProblem(SerializerProvider.java:1309)

 at com.fasterxml.jackson.databind.SerializerProvider._createAndCacheUntypedSerializer(SerializerProvider.java:1427)

 at com.fasterxml.jackson.databind.SerializerProvider.findValueSerializer(SerializerProvider.java:521)

 at com.fasterxml.jackson.databind.SerializerProvider.findTypedValueSerializer(SerializerProvider.java:799)

 at com.fasterxml.jackson.databind.ser.DefaultSerializerProvider.serializeValue(DefaultSerializerProvider.java:308)

 at com.fasterxml.jackson.databind.ObjectWriter$Prefetch.serialize(ObjectWriter.java:1513)

 at com.fasterxml.jackson.databind.ObjectWriter._configAndWriteValue(ObjectWriter.java:1215)

 at com.fasterxml.jackson.databind.ObjectWriter.writeValueAsString(ObjectWriter.java:1085)

 at com.javaprogramto.jackson.annotations.JsonAnyGetterExample.main(JsonAnyGetterExample.java:19)

Caused by: java.lang.IllegalArgumentException: Problem with definition of [AnnotedClass com.javaprogramto.jackson.annotations.Table]: Multiple 'any-getters' defined ([method com.javaprogramto.jackson.annotations.Table#getModelName(0 params)] vs [method com.javaprogramto.jackson.annotations.Table#getOtherProperties(0 params)])

 at com.fasterxml.jackson.databind.introspect.POJOPropertiesCollector.reportProblem(POJOPropertiesCollector.java:1108)

 at com.fasterxml.jackson.databind.introspect.POJOPropertiesCollector.getAnyGetter(POJOPropertiesCollector.java:225)

 at com.fasterxml.jackson.databind.introspect.BasicBeanDescription.findAnyGetter(BasicBeanDescription.java:471)

 at com.fasterxml.jackson.databind.ser.BeanSerializerFactory.constructBeanOrAddOnSerializer(BeanSerializerFactory.java:419)

 at com.fasterxml.jackson.databind.ser.BeanSerializerFactory.findBeanOrAddOnSerializer(BeanSerializerFactory.java:286)

 at com.fasterxml.jackson.databind.ser.BeanSerializerFactory._createSerializer2(BeanSerializerFactory.java:231)

 at com.fasterxml.jackson.databind.ser.BeanSerializerFactory.createSerializer(BeanSerializerFactory.java:165)

 at com.fasterxml.jackson.databind.SerializerProvider._createUntypedSerializer(SerializerProvider.java:1474)

 at com.fasterxml.jackson.databind.SerializerProvider._createAndCacheUntypedSerializer(SerializerProvider.java:1422)

 ... 7 more


5. @JsonAnyGetter on Setter Method


If you use it on the setter method that works similar to the without annotation on the getter method. this produces the output as same as without using @JsonAnyGetter annotation. It makes no impact on serialization when using it on the setter method.

Sometimes you see that JsonAnyGetter not working properly if you apply on the wrong method.

@JsonAnyGetter
public void setOtherProperties(Map<String, String> otherProperties) {
    this.otherProperties = otherProperties;
}


6. Conclusion


In conclusion, We've seen how to use @JsonAnyGetter on the map fields. If you want to bring the map fields under its parent or root element than that map field getter method should be annotated with @JsonAnyGetter annotation.

In the next article, you will see how to deserialize the map objects from JSON to Object with JsonAnySetter annotation.

All the code shown in this article is over GitHub.

Please leave your questions and comments on the comments section.

If you like the article, please share with your friends.

COMMENTS

BLOGGER

About Us

Author: Venkatesh - I love to learn and share the technical stuff.
Name

accumulo,1,ActiveMQ,2,Adsense,1,API,37,ArrayList,16,Arrays,7,Bean Creation,3,Bean Scopes,1,BiConsumer,1,Blogger Tips,1,Books,1,C Programming,1,Collection,5,Collections,22,Collector,1,Command Line,1,Compile Errors,1,Configurations,7,Constants,1,Control Statements,8,Conversions,6,Core Java,81,Corona India,1,Create,2,CSS,1,Date,3,Date Time API,4,Dictionary,1,Difference,1,Download,1,Eclipse,2,Efficiently,1,Error,1,Errors,1,Exception,1,Exceptions,3,Fast,1,Files,9,Float,1,Font,1,Form,1,Freshers,1,Function,3,Functional Interface,2,Garbage Collector,1,Generics,4,Git,4,Grant,1,Grep,1,HashMap,1,HomeBrew,2,HTML,2,HttpClient,2,Immutable,1,Installation,1,Interview Questions,5,Iterate,2,Jackson API,3,Java,29,Java 10,1,Java 11,5,Java 12,5,Java 13,2,Java 14,2,Java 8,66,Java 8 Difference,2,Java 8 Stream Conversions,2,java 8 Stream Examples,3,Java 9,1,Java Conversions,11,Java Design Patterns,1,Java Files,1,Java Program,2,Java Programs,65,java.lang,5,java.util. function,1,jQuery,1,Kotlin,10,Kotlin Conversions,3,Kotlin Programs,6,Lambda,1,lang,29,Leap Year,1,live updates,1,Logging,1,Mac OS,2,Math,1,Maven,1,Method References,1,Mockito,1,MongoDB,3,New Features,1,Operations,1,Optional,6,Oracle,5,Oracle 18C,1,Partition,1,Patterns,1,Programs,1,Property,1,Python,2,Quarkus,1,Read,1,Real Time,1,Recursion,2,Remove,2,Rest API,1,Schedules,1,Serialization,1,Servlet,1,Sort,1,Sorting Techniques,8,Spring,2,Spring Boot,23,Spring Email,1,Spring MVC,1,Streams,21,String,58,String Programs,9,String Revese,1,Swing,1,System,1,Tags,1,Threads,10,Tomcat,1,Tomcat 8,1,Troubleshoot,16,Unix,2,Updates,3,util,5,While Loop,1,
ltr
item
JavaProgramTo.com: Jackson API @JsonAnyGetter Annotation - Map Example
Jackson API @JsonAnyGetter Annotation - Map Example
A quick guide to use @JsonAnyGetter Annotation from Jackson API. @JsonAnyGetter example to parse and serialize the addition map key-value pair as normal properties.
https://1.bp.blogspot.com/-LTKmJl5rEfQ/XsN9xtN5ZBI/AAAAAAAACvw/_K_o4idCDxIymhPA2q7l7-FSpsyOL_u_wCLcBGAsYHQ/s640/Jackson%2BAPI%2B%2540JsonAnyGetter%2BAnnotation%2B-%2BMap%2BExample.png
https://1.bp.blogspot.com/-LTKmJl5rEfQ/XsN9xtN5ZBI/AAAAAAAACvw/_K_o4idCDxIymhPA2q7l7-FSpsyOL_u_wCLcBGAsYHQ/s72-c/Jackson%2BAPI%2B%2540JsonAnyGetter%2BAnnotation%2B-%2BMap%2BExample.png
JavaProgramTo.com
https://www.javaprogramto.com/2020/05/jackson-jsonanygetter.html
https://www.javaprogramto.com/
https://www.javaprogramto.com/
https://www.javaprogramto.com/2020/05/jackson-jsonanygetter.html
true
3124782013468838591
UTF-8
Loaded All Posts Not found any posts VIEW ALL Readmore Reply Cancel reply Delete By Home PAGES POSTS View All RECOMMENDED FOR YOU LABEL ARCHIVE SEARCH ALL POSTS Not found any post match with your request Back Home Sunday Monday Tuesday Wednesday Thursday Friday Saturday Sun Mon Tue Wed Thu Fri Sat January February March April May June July August September October November December Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec just now 1 minute ago $$1$$ minutes ago 1 hour ago $$1$$ hours ago Yesterday $$1$$ days ago $$1$$ weeks ago more than 5 weeks ago Followers Follow THIS PREMIUM CONTENT IS LOCKED STEP 1: Share to a social network STEP 2: Click the link on your social network Copy All Code Select All Code All codes were copied to your clipboard Can not copy the codes / texts, please press [CTRL]+[C] (or CMD+C with Mac) to copy Table of Content