- No suggested jump to results
- Notifications
Core annotations (annotations that only depend on jackson-core) for Jackson data processor

FasterXML/jackson-annotations
Name already in use.
Use Git or checkout with SVN using the web URL.
Work fast with our official CLI. Learn more .
- Open with GitHub Desktop
- Download ZIP
Sign In Required
Please sign in to use Codespaces.
Launching GitHub Desktop
If nothing happens, download GitHub Desktop and try again.
Launching Xcode
If nothing happens, download Xcode and try again.
Launching Visual Studio Code
Your codespace will open once ready.
There was a problem preparing your codespace, please try again.
Latest commit
- 763 commits
This project contains general purpose annotations for Jackson Data Processor, used on value and handler types. The only annotations not included are ones that require dependency to the Databind package . Note that only annotations themselves (and related value classes) are included, but no functionality that uses annotations.
Project contains versions 2.0 and above: source code for earlier (1.x) versions is available from Jackson-1 repository.
Full Listing of Jackson Annotations details all available annotations; Project Wiki gives more details.
Project is licensed under Apache License 2.0 .
Usage, general
Improvements over typical java annotations.
In addition to regular usage (see below), there are couple of noteworthy improvements Jackson does:
- Mix-in annotations allow associating annotations on third-party classes ''without modifying classes''.
- Jackson annotations support full inheritance: meaning that you can ''override annotation definitions'', and not just class annotations but also method/field annotations!
Maven, Java package
All annotations are in Java package com.fasterxml.jackson.annotation . To use annotations, you need to use Maven dependency:
or download jars from Maven repository (or via quick links on Wiki )
Usage, simple
Let's start with simple use cases: renaming or ignoring properties, and modifying types that are used.
Note: while examples only show field properties, same annotations would work with method (getter/setter) properties.
Annotations for renaming properties
One of most common tasks is to change JSON name used for a property: for example:
would result in JSON like:
Annotations for Ignoring properties
Sometimes POJOs contain properties that you do not want to write out, so you can do:
and get JSON like:
or, you may get properties in JSON that you just want to skip: if so, you can use:
which would be able to handle JSON like:
Finally, you may even want to just ignore any "extra" properties from JSON (ones for which there is no counterpart in POJO). This can be done by adding:
Annotations for choosing more/less specific types
Sometimes the type Jackson uses when reading or writing a property is not quite what you want:
- When reading (deserializing), declared type may be a general type, but you know which exact implementation type to use
- When writing (serializing), Jackson will by default use the specific runtime type; but you may not want to include all information from that type but rather just contents of its supertype.
These cases can be handled by following annotations:
Usage, intermediate
Using constructors or factory methods.
By default, Jackson tries to use the "default" constructor (one that takes no arguments), when creating value instances. But you can also choose to use another constructor, or a static factory method to create instance. To do this, you will need to use annotation @JsonCreator , and possibly @JsonProperty annotations to bind names to arguments:
@JsonCreator can be used similarly for static factory methods. But there is also an alternative usage, which is so-called "delegating" creator:
the difference being that the creator method can only take one argument, and that argument must NOT have @JsonProperty annotation.
Handling polymorphic types
If you need to read and write values of Objects where there are multiple possible subtypes (i.e. ones that exhibit polymorphism), you may need to enable inclusion of type information. This is needed so that Jackson can read back correct Object type when deserializing (reading JSON into Objects). This can be done by adding @JsonTypeInfo annotation on ''base class'':
which gives serialized JSON like:
Alternatively, @JsonTypeInfo(use=DEDUCTION) can be used to avoid requiring the 'type' field. For deserialization, types are deduced based on the fields available. Exceptions will be raised if subtypes do not have a distinct signature of fieldnames or JSON does not resolve to single known signature.
Note that @JsonTypeInfo has lots of configuration possibilities: for more information check out Intro to polymorphic type handling
Changing property auto-detection
The default Jackson property detection rules will find:
- All ''public'' fields
- All ''public'' getters ('getXxx()' methods)
- All setters ('setXxx(value)' methods), ''regardless of visibility'')
But if this does not work, you can change visibility levels by using annotation @JsonAutoDetect . If you wanted, for example, to auto-detect ALL fields (similar to how packages like GSON work), you could do:
or, to disable auto-detection of fields altogether:
Community support
Jackson components are supported by the Jackson community through mailing lists, Gitter forum, Github issues. See Participation, Contributing for full details.
Enterprise support
Available as part of the Tidelift Subscription.
The maintainers of jackson-annotations and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. Learn more.
Further reading
Project-specific documentation:
- Full Listing of Jackson Annotations details all available annotations.
- jackson-annotations wiki
Backwards compatibility:
- You can make Jackson 2 use Jackson 1 annotations with jackson-legacy-introspector
- Databinding module has more documentation, since it is the main user of annotations.
Security policy
Sponsor this project, used by 184k.
Contributors 35
- Coding Ground
- Corporate Training

- Jackson Annotations Tutorial
- Jackson - Home
- Serialization Annotations
- Jackson - @JsonAnyGetter
- Jackson - @JsonGetter
- @JsonPropertyOrder
- Jackson - @JsonRawValue
- Jackson - @JsonValue
- Jackson - @JsonRootName
- Jackson - @JsonSerialize
- Deserialization Annotations
- Jackson - @JsonCreator
- Jackson - @JacksonInject
- Jackson - @JsonAnySetter
- Jackson - @JsonSetter
- Jackson - @JsonDeserialize
- @JsonEnumDefaultValue
- Property Inclusion Annotations
- @JsonIgnoreProperties
- Jackson - @JsonIgnore
- Jackson - @JsonIgnoreType
- Jackson - @JsonInclude
- Jackson - @JsonAutoDetect
- Type Handling Annotations
- Jackson - @JsonTypeInfo
- Jackson - @JsonSubTypes
- Jackson - @JsonTypeName
- General Annotations
- Jackson - @JsonProperty
- Jackson - @JsonFormat
- Jackson - @JsonUnwrapped
- Jackson - @JsonView
- @JsonManagedReference
- @JsonBackReference
- Jackson - @JsonIdentityInfo
- Jackson - @JsonFilter
- Miscellaneous
- Custom Annotation
- MixIn Annotations
- Disable Annotation
- Jackson Annotations Resources
- Jackson - Quick Guide
- Jackson - Useful Resources
- Jackson - Discussion
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
Jackson Annotations - Quick Guide
Jackson annotations - @jsonanygetter.
@JsonAnyGetter allows a getter method to return Map which is then used to serialize the additional properties of JSON in the similar fashion as other properties.
Example without @JsonAnyGetter
Example with @jsonanygetter, jackson annotations - @jsongetter.
@JsonGetter allows a specific method to be marked as getter method.
Example without @JsonGetter
Example with @jsongetter, jackson annotations - @jsonpropertyorder.
@JsonPropertyOrder allows a specific order to be preserved while serializing a JSON object.
Example without @JsonPropertyOrder
Example @jsonpropertyorder, jackson annotations - @jsonrawvalue.
@JsonRawValue allows to serialize a text without escaping or without any decoration.
Example without @JsonRawValue
Example with @jsonrawvalue, jackson annotations - @jsonvalue.
@JsonValue allows to serialize an entire object using its single method.
Example @JsonValue
Jackson annotations - @jsonrootname.
@JsonRootName allows to have a root node specified over the JSON. We need to enable wrap root value as well.
Example @JsonRootName
Jackson annotations - @jsonserialize.
@JsonSerialize is used to specify custom serializer to marshall the json object.
Example with @JsonSerialize
Jackson annotations - @jsoncreator.
@JsonCreator is used to fine tune the constructor or factory method used in deserialization. We'll be using @JsonProperty as well to achieve the same. In the example below, we are matching an json with different format to our class by defining the required property names.
Example @JsonCreator
Jackson annotations - @jacksoninject.
@JacksonInject is used when a property value is to be injected instead of being parsed from Json input. In the example below, we are inserting a value into object instead of parsing from the Json.
Example @JacksonInject
Jackson annotations - @jsonanysetter.
@JsonAnySetter allows a setter method to use Map which is then used to deserialize the additional properties of JSON in the similar fashion as other properties.
Example @JsonAnySetter
Jackson annotations - @jsonsetter.
@JsonSetter allows a specific method to be marked as setter method.
Example @JsonSetter
Jackson annotations - @jsondeserialize.
@JsonDeserialize is used to specify custom deserializer to unmarshall the json object.
Example @JsonDeserialize
Jackson annotations - @jsonenumdefaultvalue.
@JsonEnumDefaultValue is used to deserialize an unknown enum value using a default value.
Example @JsonEnumDefaultValue
Jackson annotations - @jsonignoreproperties.
@JsonIgnoreProperties is used at class level to mark a property or list of properties to be ignored.
Example - @JsonIgnoreProperties
Jackson annotations - @jsonignore.
@JsonIgnore is used at field level to mark a property or list of properties to be ignored.
Example - @JsonIgnore
Jackson annotations - @jsonignoretype.
@JsonIgnoreType is used at mark a property of special type to be ignored.
Example - @JsonIgnoreType
Jackson annotations - @jsoninclude.
@JsonInclude is used at exclude properties having null/empty or default values.
Example - @JsonInclude
Jackson annotations - @jsonautodetect.
@JsonAutoDetect can be used to include properties which are not accessible otherwise.
Example - @JsonAutoDetect
Jackson annotations - @jsontypeinfo.
@JsonTypeInfo is used to indicate details of type information which is to be included in serialization and de-serialization.
Example - @JsonTypeInfo
Jackson annotations - @jsonsubtypes.
@JsonSubTypes is used to indicate subtypes of types annotated.
Example - @JsonSubTypes
Jackson annotations - @jsontypename.
@JsonTypeName is used to set type names to be used for annotated class.
Example - @JsonTypeName
Jackson annotations - @jsonproperty.
@JsonProperty is used to mark non-standard getter/setter method to be used with respect to json property.
Example - @JsonProperty
Jackson annotations - @jsonformat.
@JsonFormat is used to specify format while serialization or de-serialization. It is mostly used with Date fields.
Example - @JsonFormat
Jackson annotations - @jsonunwrapped.
@JsonUnwrapped is used to unwrap values of objects during serialization or de-serialization.
Example - @JsonUnwrapped
Jackson annotations - @jsonview.
@JsonView is used to control values to be serialized or not.
Example - @JsonView
Jackson annotations - @jsonmanagedreference.
@JsonManagedReferences and JsonBackReferences are used to display objects with parent child relationship. @JsonManagedReferences is used to refer to parent object and @JsonBackReferences is used to mark child objects.
Example - @JsonManagedReferences
Jackson annotations - @jsonbackreference, example - @jsonbackreferences, jackson annotations - @jsonidentityinfo.
@JsonIdentityInfo is used when objects have parent child relationship. @JsonIdentityInfo is used to indicate that object identity will be used during serialization/de-serialization.
Example - @JsonIdentityInfo
Jackson annotations - @jsonfilter.
@JsonFilter is used to apply filter during serialization/de-serialization like which properties are to be used or not.
Example - @JsonFilter
Jackson annotations - custom annotation.
We can create custom annotation easily using @JacksonAnnotationsInside annotation.
Example - Custom Annotation
Jackson annotations - mixin.
Mixin Annotation is a way to associate annotations without modifying the target class. See the example below −
Example - Mixin Annotation
Jackson annotations - disable.
We can disable jackson annotations using disable() function of ObjectMapper.
Example - Disabling Annotation
Spring Framework Guru
Jackson annotations for json.

Jackson is a suite of data-processing tools for Java comprising of three components:
- Streaming (jackson-core) defines low-level streaming API and includes JSON-specific implementations.
- Annotations (jackson-annotations) contains standard Jackson annotations.
- Databind (jackson-databind) implements data-binding (and object serialization) support on streaming package. This package depends both on streaming and annotations packages
In this post, I will explain the Java objects to JSON data-binding using Jackson annotations. I will take up each of the Jackson annotations and explain with code snippets how to use them. Each annotation usage is accompanied with proper test cases.
Jackson Serialization and Deserialization Annotations
The Jackson library provides annotations that you can use in POJO’s to control both serialization and deserialization between POJOs and JSON. Below are annotations used in both serialization and deserialization operations:
@JsonIgnore
@jsonignoreproperties, @jsonignoretype, @jsonautodetect.
The @JsonIgnore annotation marks a field in a POJO to be ignored by Jackson during serialization and deserialization. Jackson ignores the field in both JSON serialization and deserialization. An example of Java class that uses the @JsonIgnore annotation is this.
IgnoreDemoBean.java
The test class to the @JsonIgnore annotation is this.
IgnoreDemoBeanTest.java
As you can see, the @JsonIgnore annotation ignored the field personId during serialization and deserialization.
The @JsonIgnoreProperties annotation is used at the class level to ignore fields during serialization and deserialization. The properties that are declared in this annotation will not be mapped to the JSON content.
Let us consider an example of Java class that uses the @JsonIgnoreProperties annotation.
IgnorePropertiesDemoBean.java
The test code to the @JsonIgnoreProperties annotation is this.
IgnorePropertiesDemoBeanTest
The output of running the test in IntelliJ is this.
The @JsonIgnoreType annotation is used to mark a class to be ignored during serialization and deserialization. It marks all the properties of the class to be ignored while generating and reading JSON. An example of Java class that uses the @JsonIgnoreType annotation is this.
IgnoreTypeDemoBean.java
Ignoretypedemobeantest.java.
The @JsonAutoDetect annotation is used at the class level to tell Jackson to override the visibility of the properties of a class during serialization and deserialization. You can set the visibility with the following elements:
- creatorVisibility
- fieldVisibility
- getterVisibility
- setterVisibility
- isGetterVisibility
The JsonAutoDetect class defines public static constants that are similar to Java class visibility levels. They are:
- NON_PRIVATE
- PROTECTED_AND_PRIVATE
- PUBLIC_ONLY
Let us consider an example of Java class that uses the @JsonAutoDetect annotation.
AutoDetectDemoBean.java
The test code to the @JsonAutoDetect annotation is this.
Jackson Serialization Annotations
Jackson provides several annotations that you can use in POJO’s to serialize Java objects to JSON. These annotations are:
@JsonInclude
@jsongetter, @jsonanygetter, @jsonpropertyorder, @jsonrawvalue, @jsonserialize, @jsonrootname.
The @JsonValue annotation is used at the method level. This annotation tells Jackson to use this method to generate the JSON string from the Java object.
Typically, if you want to print a serialized object, you override the toString() method. But, by using the @JsonValue annotation, you can define the way in which the Java object is to be serialized.
Note: Jackson omits any quotation marks inside the String that is returned by the custom serializer.
Let us consider an example Java class that uses the @JsonValue annotation.
ValueDemoBean.java
In order to explain the difference between the serialized object with and without the @JsonValue annotation, the code includes the toString() method. You can also run the code without overriding the toString() method.
The code to test the @JsonValue annotation is this.
ValueDemoBeanTest
As shown in the preceding figure, the Java object is serialized by Jackson by calling the defined method toJson() . The quotation marks are added by Jackson.
The @JsonInclude annotation is used to exclude properties or fields of a class under certain conditions. This is defined using the JsonInclude.Include enum. This enum contains constants, that determine whether or not to exclude the property. The constants are:
- NON_DEFAULT
Let us consider an example Java class that uses the @JsonInclude annotation.
IncludeDemoBean.java
The test code to the @JsonInclude annotation is this.
As shown in the preceding figure, the JSON string does not contain the property name as it is initialized to null.
The @JsonGetter annotation is used to customize the generated JSON keys. This is accomplished with the value argument of @JsonGetter . The value passed is the name that should be used as the JSON key.
Let us consider an example Java class that uses the @JsonGetter annotation.
GetterDemoBean.java
The code to test the @JsonGetter annotation is this.
As you can see in the example, the Java object is serialized with the property names that you defined using the @JsonGetter annotation. Without the annotations, the serialized JSON would contain the property names: personId and personName .
The @JsonAnyGetter annotation can be used when you don’t want to declare a property or a method for every possible key in JSON. This annotation is used on the getter methods, which enables you to use a Map to hold all your properties that you want to serialize.
Let us consider an example Java class that uses the @JsonAnyGetter annotation.
AnyGetterDemoBean.java
The code to test the @JsonAnyGetter annotation is this.
The @JsonPropertyOrder annotation tells Jackson to serialize the Java object to JSON, in the order specified as the arguments of the annotation. This annotation also allows partial ordering. The properties are first serialized in the order, in which they are found. Followed by any other properties not included in the annotation.
Let us consider an example of Java class that uses the @JsonPropertyOrder annotation.
PropertyOrderDemoBean.java
The test code to the @JsonPropertyOrder annotation is this.
As you can see the result, the name property is first serialized before the personId . Without the @JsonPropertyOrder annotation, the object would have been serialized in the order found in the class.
The @JsonRawValue annotation is used on methods and fields. It tells Jackson to serialize the field or property as declared. For example, if you have a String field in your Java class, the JSON value that Jackson generates is enclosed within quotes (” “). But when you annotate the field with @JsonRawValue , Jackson omits the quotes.
Let us consider an example Java class that explains the use of @JsonRawValue .
RawValueDemoBean.java
Here, the address field is a JSON string. This JSON string will be serialized as a part of the final JSON string of the RawValueDemoBean object.
The test code to test the @JsonRawValue annotation is this.
As you can see, the final JSON string of the Java object is generated as defined in the POJO class omitting the quotes.
The @JsonSerialize annotation is used tell Jackson to use the declared custom serializer during the serialization of the field, which is marked with this annotation. Let us consider a POJO that uses the @JsonSerialize annotation.
SerializeDemoBean.java
Next, let us define a custom serializer that will serialize the activeDate field with a specific format.
CustomDateSerializer.java
The code to test the @JsonSerialize annotation is this.
The @JsonRootName annotation can be used to tell Jackson to wrap the object to be serialized with a top-level element. You can pass the name as a parameter to the @JsonRootName annotation. Let us consider that you want to wrap your serialized Java object with the key user .
Here is an example of Java class that uses the @JsonRootName annotation.
RootNameDemoBean.java
The code to test the @JsonRootName annotation is this.
As you can see, the fields personId and name are wrapped within the user, where the latter is the key, and the former is the value of the property of the generated JSON.
Deserialization Annotations
Let us explore the JSON annotations that can be used to control deserialization of JSON into POJOs. The Jackson deserialization annotations are:
@JsonSetter
@jsonanysetter, @jsoncreator, @jacksoninject, @jsondeserialize.
The @JsonSetter annotation tells Jackson to deserialize the JSON into Java object using the name given in the setter method. Use this annotation when your JSON property names are different to the fields of the Java object class, and you want to map them.
A Java class that uses the @JsonSetter annotation is this.
SetterDemoBean.java
The @JsonSetter annotation takes the name of the JSON key that must be mapped to the setter method.
The test code to test the @JsonSetter annotation is this.
As you can see, the JSON to be serialized has a property id . But no field in the POJO matches this property. Now how will Jackson read this JSON? Here is where the @JsonSetter annotation can be used to map the property id to the field personId . This annotation instructs Jackson to use a setter method for a given JSON property.
The @JsonAnySetter annotation is used on setter methods of a Map field. Sometimes, you may find some JSON values that cannot be mapped to the fields in the Java object class. In such a case, the @JsonAnySetter captures the data and stores them in a Map .
A Java class that uses the @JsonAnySetter annotation is this.
AnySetterDemoBean.java
The test code to test the @JsonAnySetter annotation is this.
The @JsonCreator annotation tells Jackson that the JSON properties can be mapped to the fields of a constructor of the POJO. This is helpful when the JSON properties do not match with the names of the Java object field names. The @JsonCreator annotation can be used where @JsonSetter cannot be used. For example, immutable objects which need their initial values to be injected through constructors.
An example of Java class that uses the @JsonCreator annotation is this.
CreatorDemoBean.java
The test code to test the @JsonCreator annotation is this.
The @JacksonInject annotation is used to tell Jackson that particular values of the deserialized object will be injected and not read from the JSON string.
An example of Java class where the personId field is injected by Jackson is this.
JacksonInjectDemoBean.java
In order to inject values into a field, you can use the InjectableValues class. You need to configure ObjectMapper to read both, the injected values from injectableValues and the remaining values from the JSON string.
The test code to test the @JacksonInject annotation is this.
As you can see, the value for the field personId has been injected by Jackson and the other values are taken from the input JSON string.
The @JsonDeserialize annotation tells Jackson to use a custom deserializer while deserializing the JSON to Java object. To do so, you need to annotate the field to which you need to apply the custom deserializer.
A Java class that uses the @JsonDeserialize annotation is this.
DeserializeDemoBean.java
The custom deserializer that is referenced by the preceding DeserializeDemoBean bean class is this.
CustomDateDeserializer.java
Here, the CustomDateDeserializer class extends the StdDeserializer class with a generic type Date . The overriden deserialize() method returns the Date object.
The test code to test the @JsonDeserialize annotation is this.
General Annotations
The general annotations are:
@JsonProperty
@jsonformat, @jsonunwrapped, @jsonmanagedreference and @jsonbackreference, @jsonidentityinfo, @jsonfilter.
The @JsonProperty annotation is used to map property names with JSON keys during serialization and deserialization. By default, if you try to serialize a POJO, the generated JSON will have keys mapped to the fields of the POJO. If you want to override this behavior, you can use the @JsonProperty annotation on the fields. It takes a String attribute that specifies the name that should be mapped to the field during serialization.
You can also use @JsonProperty annotation during deserialization when the property names of the JSON and the field names of the Java object do not match.
Let us consider an example Java class that uses the @JsonProperty annotation.
PropertyDemoBean.java
The test code to test the @JsonProperty annotation is this.
The @JsonFormat annotation is used to tell Jackson that the format in which the value for a field is serialized. It specifies the format using the JsonFormat.Shape enum.
Let us consider an example Java class that uses the @JsonFormat annotation to modify the Date and Time format of an activeDate field.
FormatDemoBean.java
The test code to test the @JsonFormat annotation is this.
The @JsonUnwrapped annotation unwraps the values during serialization and deserialization. It helps in rendering the values of a composed class as if they belonged to the parent class. Let us consider an example of Java class that uses the @JsonUnwrapped annotation.
UnwrappedDemoBean.java
In this example, the Address class is inside the UnwrappedDemoBean class. Without the @JsonUnwrapped annotation, the serialized Java object would be similar to this.
Let us see what happens when you use the @JsonUnwrapped annotation.
The test code to test the @JsonUnwrapped annotation is this.
As you can see, the Address object is unwrapped and is displayed as the properties of the parent class UnwrappedDemoBean .
The @JsonView annotation is used to include or exclude a property dynamically during serialization and deserialization, and tells the view in which the properties are rendered. Let us consider an example Java class that uses the @JsonView annotation with Public and Internal views.
ViewDemoBean.java
The test code to test the @JsonView annotation is this.
As you can see in the test code, you need to configure the ObjectMapper to include which type of view must be used for writing the JSON from the Java object using the writerWithView() method.
The @JsonManagedReference and @JsonBackReference annotation are used to create JSON structures that have a bidirectional relationship. Without this annotation, you get an error like this.
Let us consider an example Java class that uses the @JsonManagedReference and @JsonBackReference annotations.
ManagedReferenceDemoBean.java
Backreferencedemobean.java.
The test code to test both @JsonManagedReference and @JsonBackReference annotations is this.
As you can see, the field marked with @JsonManagedReference is the forward reference which will be included during serialization. The field marked with @JsonBackReference is the back reference and is usually omitted during serialization.
The @JsonIdentityInfo tells Jackson to perform serialization or deserialization using the identity of the object. This annotation works similar to the @JsonManagedReference and @JsonBackReference annotations with the difference that @JsonIdentityInfo includes the back reference object.
Let us consider an example where the IdentityInfoEmployeeDemoBean has a bidirectional relationship with IdentityInfoManagerDemoBean using the @JsonIdentityInfo annotation.
IdentityInfoEmployeeDemoBean.java
Identityinfomanagerdemobean.java.
The test code to test the @JsonIdentityInfo annotation is this.
As you can see, the output gives the information about the employee with his manager details and information about the employees under the manager.
The @JsonFilter annotation is used to tell Jackson to use a custom defined filter to serialize the Java object. To define your filter, you need to use the FilterProvider class. This provider gets the actual filter instance to use. The filter is then configured by assigning the FilterProvider to ObjectMapper .
Let us consider an example of Java class that uses the @JsonFilter annotation.
FilterDemoBean.java
The test code to test the @JsonFilter annotation is this.
You can download the source code of this post from here .
You May Also Like

Hikari Configuration for MySQL in Spring Boot 2

What is New in Java 17?

Using Deque in Java

EnumSet in Java

Using ImmutableList in Java

Convert OffsetDateTime to SQL TimeStamp

Parameterized Tests in JUnit 5
Using mapstruct with project lombok.

ArgumentCaptor in Mockito

Common List Operations

Using Records in Java

Testing Spring Boot RESTful Services


Comparison and Sorting with Lambda

The New Switch Case Features

Immutable Property Binding

Java Bean Properties Binding

Convert OffsetDateTime to LocalDateTime

Convert OffsetDateTime to ZonedDateTime

Feign REST Client for Spring Application

Using jEnv for Setting the JAVA_HOME Path

Consul Miniseries: Spring Boot Application and Consul Integration Part 2

Consul Miniseries: Spring Boot Application and Consul Integration Part 1

Java 14 records

Using SDKMAN for Your Development Environment
Debug your code in intellij idea, stay at home, learn from home with 6 free online courses.

Spring Boot with Lombok: Part 1

Using Project Lombok with Gradle
Autowiring in spring.

Service Locator Pattern in Spring
Spring jdbctemplate crud operations.

Java ArrayList vs LinkedList

Java HashMap vs Hashtable

Sorting Java Collections

Iterating Over Collections In Java

Is String A Palindrome?

Using SDKMAN To Manage Java Versions
Installing maven.

Merge Sort in Java

Why Your JUnit 5 Tests Are Not Running Under Maven

Converting between Java List and Array

Using Java Enums

Converting Java Map to List

Java String to Int

Using JAXB for XML with Java

Java 8 forEach
Jackson mix-in annotation.

Enable Pretty Print of JSON with Jackson

Random Number Generation in Java
Google gson for json processing.

Mockito Mock vs Spy in Spring Boot Tests
Running spring boot in a docker container, processing json with jackson.

Jackson Dependency Issue in Spring Boot with Maven Build

Using YAML in Spring Boot to Configure Logback

Using Logback with Spring Boot
Logback configuration: using groovy.

Logback Configuration: Using XML

Iterating Java Map Entries
Logback introduction: an enterprise logging framework.

Using Log4J 2 with Spring Boot
Asynchronous logging with log4j 2.

Log4J 2 Configuration: Using YAML
Log4j 2 configuration: using json, log4j 2 configuration: using xml, log4j 2 configuration: using properties file, hibernate pagination – how to.

Introducing Log4J 2 – Enterprise Class Logging
Why i use intellij.

Java Language #1 in January 2016

Sorting Java ArrayList

Getting Current Date Time in Java
Mocking in unit tests with mockito, you should use jaxb generated classes for restful web services.

Unit Testing with JUnit – Part 4 –Parameterized and Theories
Unit testing with junit – part 3 – hamcrest matchers, unit testing with junit – part 2.

Spring Boot Web Application – Part 3 – Spring Data JPA

Unit Testing with JUnit – Part 1
Integration testing with spring and junit.

Testing Software

Monetary Calculation Pitfalls

Polymorphism in Java

Introduction to Java Variables

Hello World With Spring 4

Getting Started With Spring Boot

What’s all the fuss about Java Lambdas?
3 comments on “ jackson annotations for json ”.
simonmichel
Your code in sample “AutoDetectDemoBean.java” is missing.
nice writeup, from where we can download source code for the examples in your blog..
Nelson Visbal
In the first example “productId” doesn’t exists in the “IgnoreDemoBean.java” class
@Test public void testSerializingWithJsonIgnore() throws JsonProcessingException { String jsonString = objectMapper.writeValueAsString(new IgnoreDemoBean()); System.out.println(jsonString); assertThat(jsonString, containsString(“James Clark”)); assertThat(jsonString, not(containsString(“productId”))); }
Leave a Reply Cancel Reply
Your email address will not be published. Required fields are marked *
Save my name, email, and website in this browser for the next time I comment.
This site uses Akismet to reduce spam. Learn how your comment data is processed .
- Data Structure & Algorithm Classes (Live)
- System Design (Live)
- DevOps(Live)
- Explore More Live Courses
- Interview Preparation Course
- Data Science (Live)
- GATE CS & IT 2024
- Data Structure & Algorithm-Self Paced(C++/JAVA)
- Data Structures & Algorithms in Python
- Explore More Self-Paced Courses
- C++ Programming - Beginner to Advanced
- Java Programming - Beginner to Advanced
- C Programming - Beginner to Advanced
- Android App Development with Kotlin(Live)
- Full Stack Development with React & Node JS(Live)
- Java Backend Development(Live)
- React JS (Basic to Advanced)
- JavaScript Foundation
- Complete Data Science Program(Live)
- Mastering Data Analytics
- CBSE Class 12 Computer Science
- School Guide
- All Courses
- Linked List
- Binary Tree
- Binary Search Tree
- Advanced Data Structure
- All Data Structures
- Asymptotic Analysis
- Worst, Average and Best Cases
- Asymptotic Notations
- Little o and little omega notations
- Lower and Upper Bound Theory
- Analysis of Loops
- Solving Recurrences
- Amortized Analysis
- What does 'Space Complexity' mean ?
- Pseudo-polynomial Algorithms
- Polynomial Time Approximation Scheme
- A Time Complexity Question
- Searching Algorithms
- Sorting Algorithms
- Graph Algorithms
- Pattern Searching
- Geometric Algorithms
- Mathematical
- Bitwise Algorithms
- Randomized Algorithms
- Greedy Algorithms
- Dynamic Programming
- Divide and Conquer
- Backtracking
- Branch and Bound
- All Algorithms
- Company Preparation
- Practice Company Questions
- Interview Experiences
- Experienced Interviews
- Internship Interviews
- Competitive Programming
- Design Patterns
- System Design Tutorial
- Multiple Choice Quizzes
- Go Language
- Tailwind CSS
- Foundation CSS
- Materialize CSS
- Semantic UI
- Angular PrimeNG
- Angular ngx Bootstrap
- jQuery Mobile
- jQuery EasyUI
- React Bootstrap
- React Rebass
- React Desktop
- React Suite
- ReactJS Evergreen
- ReactJS Reactstrap
- BlueprintJS
- TensorFlow.js
- English Grammar
- School Programming
- Number System
- Trigonometry
- Probability
- Mensuration
- Class 8 Syllabus
- Class 9 Syllabus
- Class 10 Syllabus
- Class 8 Notes
- Class 9 Notes
- Class 10 Notes
- Class 11 Notes
- Class 12 Notes
- Class 8 Maths Solution
- Class 9 Maths Solution
- Class 10 Maths Solution
- Class 11 Maths Solution
- Class 12 Maths Solution
- Class 7 Notes
- History Class 7
- History Class 8
- History Class 9
- Geo. Class 7
- Geo. Class 8
- Geo. Class 9
- Civics Class 7
- Civics Class 8
- Business Studies (Class 11th)
- Microeconomics (Class 11th)
- Statistics for Economics (Class 11th)
- Business Studies (Class 12th)
- Accountancy (Class 12th)
- Macroeconomics (Class 12th)
- Machine Learning
- Data Science
- Mathematics
- Operating System
- Computer Networks
- Computer Organization and Architecture
- Theory of Computation
- Compiler Design
- Digital Logic
- Software Engineering
- GATE 2024 Live Course
- GATE Computer Science Notes
- Last Minute Notes
- GATE CS Solved Papers
- GATE CS Original Papers and Official Keys
- GATE CS 2023 Syllabus
- Important Topics for GATE CS
- GATE 2023 Important Dates
- Software Design Patterns
- HTML Cheat Sheet
- CSS Cheat Sheet
- Bootstrap Cheat Sheet
- JS Cheat Sheet
- jQuery Cheat Sheet
- Angular Cheat Sheet
- Facebook SDE Sheet
- Amazon SDE Sheet
- Apple SDE Sheet
- Netflix SDE Sheet
- Google SDE Sheet
- Wipro Coding Sheet
- Infosys Coding Sheet
- TCS Coding Sheet
- Cognizant Coding Sheet
- HCL Coding Sheet
- FAANG Coding Sheet
- Love Babbar Sheet
- Mass Recruiter Sheet
- Product-Based Coding Sheet
- Company-Wise Preparation Sheet
- Array Sheet
- String Sheet
- Graph Sheet
- ISRO CS Original Papers and Official Keys
- ISRO CS Solved Papers
- ISRO CS Syllabus for Scientist/Engineer Exam
- UGC NET CS Notes Paper II
- UGC NET CS Notes Paper III
- UGC NET CS Solved Papers
- Campus Ambassador Program
- School Ambassador Program
- Geek of the Month
- Campus Geek of the Month
- Placement Course
- Testimonials
- Student Chapter
- Geek on the Top
- Geography Notes
- History Notes
- Science & Tech. Notes
- Ethics Notes
- Polity Notes
- Economics Notes
- UPSC Previous Year Papers
- SSC CGL Syllabus
- General Studies
- Subjectwise Practice Papers
- Previous Year Papers
- SBI Clerk Syllabus
- General Awareness
- Quantitative Aptitude
- Reasoning Ability
- SBI Clerk Practice Papers
- SBI PO Syllabus
- SBI PO Practice Papers
- IBPS PO 2022 Syllabus
- English Notes
- Reasoning Notes
- Mock Question Papers
- IBPS Clerk Syllabus
- Apply for a Job
- Apply through Jobathon
- Hire through Jobathon
- All DSA Problems
- Problem of the Day
- GFG SDE Sheet
- Top 50 Array Problems
- Top 50 String Problems
- Top 50 Tree Problems
- Top 50 Graph Problems
- Top 50 DP Problems
- Solving For India-Hackthon
- GFG Weekly Coding Contest
- Job-A-Thon: Hiring Challenge
- BiWizard School Contest
- All Contests and Events
- Saved Videos
- What's New ?
- Data Structures
- Interview Preparation
- Topic-wise Practice
- Latest Blogs
- Write & Earn
- Web Development
Related Articles
- Write Articles
- Pick Topics to write
- Guidelines to Write
- Get Technical Writing Internship
- Write an Interview Experience
- Arrays in Java
- Spring Boot - Start/Stop a Kafka Listener Dynamically
- Parse Nested User-Defined Functions using Spring Expression Language (SpEL)
- Split() String method in Java with examples
- Arrays.sort() in Java with examples
- For-each loop in Java
- Reverse a string in Java
- Object Oriented Programming (OOPs) Concept in Java
- How to iterate any Map in Java
- HashMap in Java with Examples
- Initialize an ArrayList in Java
- Multidimensional Arrays in Java
- ArrayList in Java
- Stack Class in Java
- How to add an element to an Array in Java?
- Interfaces in Java
- Overriding in Java
- Set in Java
- LinkedList in Java
- Singleton Class in Java
- Inheritance in Java
- Collections in Java
- Queue Interface In Java
- Classes and Objects in Java
- Convert a String to Character Array in Java
- Collections.sort() in Java with Examples
- Initializing a List in Java
- Multithreading in Java
- Math pow() method in Java with Example
- Polymorphism in Java
Jackson Annotations For Java Application
- Last Updated : 20 Jul, 2021
Java has immense application in the coding world, and almost all of us know this fact. One of its features is the Jackson annotations. Although that is a very familiar term with the people involved in the coding world, it is less known. Jackson is a popular and very efficient JAVA library used to map or serialize JAVA objects to JSON and vice versa.
Since Jackson is a JAVA-based library, one must know the basics of JAVA before going on with Jackson. It provides various features that are listed as below:
- Jackson is an easy-to-use library that can simplify commonly used cases.
- Since it provides default mapping, there is no need to create a mapping in Jackson.
- It has a commendable speed and low memory footprint, making it suitable for large object systems.
- The JSON results created by Jackson are compact and clean, which makes them easy to read.
- Jdk is the only library that Jackson requires. Therefore, it has no dependency.
- Above all, the Jackson library is free to use since it is open-source.
After we have learned about the use and advantages of using Jackson, we now need to understand the Jackson annotations are as follows:
- @JsonAnyGetter
- @JsonGetter
- @JsonPropertyOrder
- @JsonRawValue
- @JsonRootName
- @JsonSerialize
- @JsonCreator
- @JacksonInject
- @JsonAnySetter
- @JsonSetter
- @JsonDeserialize
- @JsonEnumDefaultValue
- @JsonIgnoreProperties
- @JsonIgnore
- @JsonIgnoreType
- @JsonInclude
- @JsonAutoDetect
- @JsonTypeInfo
- @JsonSubTypes
- @JsonTypeName
- @JsonProperty
- @JsonFormat
- @JsonUnwrapped
- @JsonManagedReference
- @JsonBackReference
- @JsonIdentityInfo
- @JsonFilter
- @JacksonAnnotationsInside
Let us discuss each of the annotations in order to understand them to deeper roots by implementing them providing fragment codes for all of them.
Annotation 1: @JsonAnyGetter
t facilitates a return of Maps using a getter method. Later the maps are used to serialize the additional properties of JSON in the same way as other properties.
Annotation 2: @JsonGetter
This annotation facilitates the marking of a specific method as a getter method.
Annotation 3: @JsonPropertyOrder
While you serialize a JSON object, its order might change, but this annotation facilitates preserving a specific order while the process goes on.
Annotation 4: @JsonRawValue
Using this annotation, one can serialize any word without any decoration or escape.
Annotation 5: @JsonValue
Using this annotation, you can serialize an entire object using a single method.
Annotation 6: @JsonRootName
This annotation facilitates the appearance of a root node specified over JSON. Wrap root value also needs to be enabled.
Annotation 7: @JsonSerialize
Using this annotation, you can specify a custom serializer to marshall the JSON object.
Annotation 8: @JsonCreator
During deserialization, there is a factory method used. This annotation is used to fine-tune this method.
Annotation 9: @JacksonInject
When we do not have to parse the property value, instead inject it in the JSON input, we use this annotation.
Annotation 10: @JsonAnySetter
Just as the getter annotation, this facilitates a setter method for using Map, which is then used to deserialize the additional properties of JSON in the same manner as other properties.
Annotation 11: @JsonSetter
This annotation allows any method to be marked as a setter method.
Annotation 12: @JsonDeserialize
This annotation is used to specify a custom deserializer in order to unmarshall a JSON object.
Annotation 13: @JsonEnumDefaultValue
Using this annotation, we use a default value for deserializing an unknown enum value.
Annotation 14: @JsonIgnoreProperties
Using this annotation, you can mark a property or a group of properties to be ignored. This is done at the class level.
Annotation 15: @JsonIgnore
This one serves the same purpose as above, the only difference being that it is used at the field level.
Annotation 16: @JsonIgnoreType
Using this annotation, you can mark the property of a specific type to be ignored.
Annotation 17: @JsonInclude
This annotation is used at those exclude properties that have null or empty default values.
Annotation 18: @JsonAutoDetect
This annotation helps detect properties that are not visible or accessible otherwise.
Annotation 19: @JsonTypeInfo
Using this annotation, you can indicate the details of the type of information that has to be included either during serialization or deserialization.
Annotation 20: @JsonSubTypes
This one is used to indicate the subtypes of the types that have been annotated.
Annotation 21: @JsonTypeName
Using this one can set type names that have to be used for annotated classes.
Annotation 22: @JsonProperty
This annotation is used to mark the non-standard setter or getter methods that have to be used concerning JSON properties.
Annotation 23: @JsonFormat
This annotation is usually used in Date fields and specifies the format during serialization or deserialization.
Annotation 24: @JsonUnwrapped
During the process of serialization or deserialization, it is required to unwrap the values of objects. This annotation is used to fulfill the purpose.
Annotation 25: @JsonView
This annotation is used to control the values to be serialized or not.
Annotation 26: @JsonManagedReference
Such annotations are used for the display of objects with a parent-child relationship.
Annotation 27: @JsonBackReference
This shares the same function as the previous one.
Annotation 28: @JsonIdentityInfo
This annotation is used in a case where there is a parent-child relationship. It is used to indicate that an object identity will be used during serialization and deserialization.
Annotation 29: @JsonFilter
This annotation can be used to apply filters during the process of serialization and deserialization.
Annotation 30: @JacksonAnnotationsInside
This annotation can be used to create customized Jackson annotations.
Note: Various other annotations are used to rename properties or ignore them or choose the more or less specific types.
While using these annotations, Jackson itself uses the default constructors while creating value instances. However, one may alter it by putting the customize constructor. Also, Jackson can handle polymorphic types, that is, objects with various subtypes. This does by enabling the inclusion of type information. Therefore, these were a few points and essential information on the Jackson annotations, their use, and their importance in Java.
Please Login to comment...
Improve your coding skills with practice, start your coding journey now.
- Java JSON Tutorial
- Jackson Installation
- Jackson ObjectMapper
- Jackson JsonNode
- Jackson JsonParser
- Jackson JsonGenerator
Jackson Annotations
- Boon - Installation
- Boon - ObjectMapper
- GSON - Installation
- GSON - Gson
- GSON - JsonReader
- GSON - JsonParser
@JsonIgnore
@jsonignoreproperties, @jsonignoretype, @jsonautodetect, @jsonsetter, @jsonanysetter, @jsoncreator, @jacksoninject, @jsondeserialize, @jsoninclude, @jsongetter, @jsonanygetter, @jsonpropertyorder, @jsonrawvalue, @jsonserialize.
The Jackson JSON toolkit contains a set of Java annotations which you can use to influence how JSON is read into objects, or what JSON is generated from the objects. This Jackson annotation tutorial explains how to use Jackson's annotations.
If you are unfamiliar with Java annotations, read my Java annotation tutorial before reading this tutorial. It will help you understand how Java annotations work.
Read + Write Annotations
Jackson contains a set of annotations that affect both the reading of Java objects from JSON, as well as the writing of Java objects into JSON. I refer to these annotations as "read + write annotations". The following sections explain Jackson's read + write annotations in more detail.
The Jackson annotation @JsonIgnore is used to tell Jackson to ignore a certain property (field) of a Java object. The property is ignored both when reading JSON into Java objects, and when writing Java objects into JSON. Here is an example class that uses the @JsonIgnore annotation:
In the above class the property personId will not be read from JSON or written to JSON.
The @JsonIgnoreProperties Jackson annotation is used to specify a list of properties of a class to ignore. The @JsonIgnoreProperties annotation is placed above the class declaration instead of above the individual properties (fields) to ignore. Here is an example showing how to use the @JsonIgnoreProperties annotation:
In this example both the properties firstName and lastName will be ignored because their names are listed inside the @JsonIgnoreProperties annotation declaration above the class declaration.
The @JsonIgnoreType Jackson annotation is used to mark a whole type (class) to be ignored everywhere that type is used. Here is an example that shows you how you could use the @JsonIgnoreType annotation:
In the above example all Address instances will be ignored.
The Jackson annotation @JsonAutoDetect is used to tell Jackson to include properties which are not public, both when reading and writing objects. Here is an example class showing you how you can use the @JsonAutoDetect annotation:
The JsonAutoDetect.Visibility class contains constants matching the visibility levels in Java, meaning ANY , DEFAULT , NON_PRIVATE , NONE , PROTECTED_AND_PRIVATE and PUBLIC_ONLY .
Read Annotations
Jackson contains a set of annotations that only affect how Jackson parses JSON into objects - meaning they affect Jackson's reading of JSON. I refer to these as "read annotations". The following sections explains Jackson's read annotations.
The Jackson annotation @JsonSetter is used to tell Jackson that is should match the name of this setter method to a property name in the JSON data, when reading JSON into objects. This is useful if the property names used internally in your Java class is not the same as the property name used in the JSON file.
The following Person class uses the name personId for its id property:
But in this JSON object the name id is used instead of personId :
Without some help Jackson cannot map the id property from the JSON object to the personId field of the Java class.
The @JsonSetter annotation instructs Jackson to use a setter method for a given JSON field. In our case we add the @JsonSetter annotation above the setPersonId() method. Here is how adding the @JsonSetter annotation looks like:
The value specified inside the @JsonSetter annotation is the name of the JSON field to match to this setter method. In this case the name is id since that is the name of the field in the JSON object we want to map to the setPersonId() setter method.
The Jackson annotation @JsonAnySetter instructs Jackson to call the same setter method for all unrecognized fields in the JSON object. By "unrecognized" I mean all fields that are not already mapped to a property or setter method in the Java object. Look at this Bag class:
And then look at this JSON object:
Jackson cannot directly map the id and name property of this JSON object to the Bag class, because the Bag class contains no public fields or setter methods.
You can tell Jackson to call the set() method for all unrecognized fields by adding the @JsonAnySetter annotation, like this:
Now Jackson will call the set() method with the name and value of all unrecognized fields in the JSON object.
Keep in mind that this only has effect on unrecognized fields. If, for instance, you added a public name property or setName(String) method to the Bag Java class, then the name field in the JSON object would be mapped to that property / setter instead.
The Jackson annotation @JsonCreator is used to tell Jackson that the Java object has a constructor (a "creator") which can match the fields of a JSON object to the fields of the Java object.
The @JsonCreator annotation is useful in situations where the @JsonSetter annotation cannot be used. For instance, immutable objects do not have any setter methods, so they need their initial values injected into the constructor. Look at this PersonImmutable class as example:
To tell Jackson that it should call the constructor of PersonImmutable we must add the @JsonCreator annotation to the constructor. But that alone is not enough. We must also annotate the parameters of the constructor to tell Jackson which fields from the JSON object to pass to which constructor parameters. Here is how the PersonImmutable class looks with the @JsonCreator and @JsonProperty annotations added:
Notice the annotation above the constructor and the annotations before the constructor parameters. Now Jackson is capable of creating a PersonImmutable from this JSON object:
The Jackson annotation @JacksonInject is used to inject values into the parsed objects, instead of reading those values from the JSON. For instance, imagine you are downloading person JSON objects from various different sources, and would like to know what source a given person object came from. The sources may not themselves contain that information, but you can have Jackson inject that into the Java objects created from the JSON objects.
To mark a field in a Java class as a field that needs to have its value injected by Jackson, add the @JacksonInject annotation above the field. Here is an example PersonInject class with the @JacksonInject annotation added above the source field:
In order to have Jackson inject values into the source field you need to do a little extra when creating the Jackson ObjectMapper . Here is what it takes to have Jackson inject values into the Java objects:
Notice how the value to inject into the source attribute is set in the InjectableValues addValue() method. Notice also that the value is only tied to the type String - not to any specific field name. It is the @JacksonInject annotation that specifies what field the value is to be injected into.
If you were to download person JSON objects from multiple sources and have a different source value injected for each source, you would have to repeat the above code for each source.
The Jackson annotation @JsonDeserialize is used to specify a custom de-serializer class for a given field in a Java object. For instance, imagine you wanted to optimize the on-the-wire formatting of the boolean values false and true to 0 and 1 .
First you would need to add the @JsonDeserialize annotation to the field you want to use the custom deserializer for. Here is how adding the @JsonDeserialize annotation to a field looks like:
Second, here is what the OptimizedBooleanDeserializer class referenced from the @JsonDeserialize annotation looks like:
Notice that the OptimizedBooleanDeserializer class extends JsonDeserializer with the generic type Boolean . Doing so makes the deserialize() method return a Boolean object. If you were to deserialize another type (e.g a java.util.Date ) you would have to specify that type inside the generics brackets (if you are new to Java generics, I have a Java Generics Tutorial too).
You obtain the value of the field to deserialize by calling the getText() method of the jsonParser parameter. You can then deserialize that text into whatever value and type your deserializer is targeted at (a Boolean in this example).
Finally you need to see what it looks like to deserialize an object with a custom deserializer and the @JsonDeserializer annotation:
Notice how we first need to create a reader for the PersonDeserialize class using the ObjectMapper 's reader() method, and then we call readValue() on the object returned by that method.
Write Annotations
Jackson also contains a set of annotations that can influence how Jackson serializes (writes) Java objects to JSON. Each of these write (serialization) annotations will be covered in the following sections.
The Jackson annotation @JsonInclude tells Jackson only to include properties under certain circumstances. For instance, that properties should only be included if they are non-null, non-empty, or have non-default values. Here is an example that shows how you can use the @JsonInclude annotation:
This example will only include the name property if the value set for it is non-empty, meaning is not null and is not an empty string.
A more saying name for the @JsonInclude annotation could have been @JsonIncludeOnlyWhen , but that would have been longer to write.
The @JsonGetter Jackson annotation is used to tell Jackson that a certain field value should be obtained from calling a getter method instead of via direct field access. The @JsonGetter annotation is useful if your Java class uses jQuery style for getter and setter names. For instance, instead of getPersonId() and setPersonId() you might have the methods personId() and personId(long id) .
Here is an example class named PersonGetter which shows the use of the @JsonGetter annotation:
As you can see, the personId() method is annotated with the @JsonGetter annotation. The value set on the @JsonGetter annotation is the name that should be used in the JSON object. Thus, the name used for the personId in the JSON object is id . The resulting JSON object would look like this:
Notice also that the personId(long personId) method is annotated with the @JsonSetter annotation to make Jackson recognized that as the setter matching the id attribute in the JSON object. The @JsonSetter annotation is used when reading from JSON into Java objects - not when writing Java objects to JSON. The @JsonSetter annotation is just included for the sake of completeness.
The @JsonAnyGetter Jackson annotation enables you to use a Map as container for properties that you want to serialize to JSON. Here is an example of using the @JsonAnyGetter annotation in a Java class:
When seeing the @JsonAnyGetter annotation Jackson will obtain the Map returned from the method which @JsonAnyGetter annotates, and will treat each key-value pair in that Map as a property. In other words, all key-value pairs in the Map will be serialized to JSON as part of the PersonAnyGetter object.
The @JsonPropertyOrder Jackson annotation can be used to specify in what order the fields of your Java object should be serialized into JSON. Here is an example showing how to use the @JsonPropertyOrder annotation:
Normally Jackson would have serialized the properties in PersonPropertyOrder in the sequence they are found in the class. However, the @JsonPropertyOrder annotation specifies a different order where the name property will be appear first and the personId property second in the serialized JSON output.
The @JsonRawValue Jackson annotation tells Jackson that this property value should written directly as it is to the JSON output. If the property is a String Jackson would normally have enclosed the value in quotation marks, but if annotated with the @JsonRawValue property Jackson won't do that.
To make it more clear what @JsonRawValue does, look at this class without the @JsonRawValue in use:
Jackson would serialize this into this JSON string:
Now we add the @JsonRawValue to the address property, like this:
Jackson will now omit the quotation marks when serializing the address property. The serialized JSON will thus look like this:
This is of course invalid JSON, so why would you want that?
Well, if the address property contained a JSON string then that JSON string would be serialized into the final JSON object as part of the JSON object structure, and not just into a string in the address field in the JSON object. To see how that would work, let us change the value of the address property like this:
Jackson would serialize this into this JSON:
Notice how the JSON string is now part of the serialized JSON structure.
Without the @JsonRawValue annotation Jackson would have serialized the object to this JSON:
Notice how the value of the address property is now enclosed in quotation marks, and all the quotation marks inside the value are escaped.
The Jackson annotation @JsonValue tells Jackson that Jackson should not attempt to serialize the object itself, but rather call a method on the object which serializes the object to a JSON string. Note that Jackson will escape any quotation marks inside the String returned by the custom serialization, so you cannot return e.g. a full JSON object. For that you should use @JsonRawValue instead (see previous section).
The @JsonValue annotation is added to the method that Jackson is to call to serialize the object into a JSON string. Here is an example showing how to use the @JsonValue annotation:
The output you would get from asking Jackson to serialize a PersonValue object is this:
The quotation marks are added by Jackson. Remember, any quotation marks in the value string returned by the object are escaped.
The @JsonSerialize Jackson annotation is used to specify a custom serializer for a field in a Java object. Here is an example Java class that uses the @JsonSerialize annotation:
Notice the @JsonSerialize annotation above the enabled field.
The OptimizedBooleanSerializer will serialize a true value to 1 and a false value 0 . Here is the code:

- Stack Overflow Public questions & answers
- Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers
- Talent Build your employer brand
- Advertising Reach developers & technologists worldwide
- About the company
Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Jackson: Object Mapper annotations to deserialize a inner collection
I want to convert the following json into a java object, using as much as possible annotations .
I'm getting trouble with the collection diets. I tried to use @JsonProperty but it doesn't work properly. Is there a special annotation for map inner aggregates?
- using as much as possible annotations. why? – Philipp Sander Aug 7, 2014 at 14:50
- Can you share your Value Object? – Syam S Aug 7, 2014 at 14:51
- I added my POJO classes. @PhilippSander, it's a personal preference. – tehAnswer Aug 7, 2014 at 14:54
The diets object in your json is not a List. Its a List of key-value pair with key "diet" and value a diet object. So you have three options here.
One is to create a wrapper object say DietWrapper and use List of diet wrapper in User like
Second option is to keep diest as simple list of maps like List>
Third option is to use a custom deserializer which would ignore your diet class.
Your Answer
Sign up or log in, post as a guest.
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service , privacy policy and cookie policy
Not the answer you're looking for? Browse other questions tagged java json jackson or ask your own question .
- The Overflow Blog
- How Intuit democratizes AI development across teams through reusability sponsored post
- The nature of simulating nature: A Q&A with IBM Quantum researcher Dr. Jamie...
- Featured on Meta
- We've added a "Necessary cookies only" option to the cookie consent popup
- Launching the CI/CD and R Collectives and community editing features for...
- The [amazon] tag is being burninated
- Temporary policy: ChatGPT is banned
- Staging Ground Beta 1 Recap, and Reviewers needed for Beta 2
Hot Network Questions
- Lagrange Points in General Relativity
- Why do academics stay as adjuncts for years rather than move around?
- What did Ctrl+NumLock do?
- Does Quantum Computers crack RSA and AES?
- how to replace the diminished chord in a key to write a good song without a diminished chord (for example e diminished to F)?
- Are demand and time deposit accounts really loans _to_ the bank?
- A story about a girl and a mechanical girl with a tattoo travelling on a train
- What laws would Jesus be breaking if he were to turn water into wine today?
- Heap implementation in C
- How would you design the following table?
- I need to identify this connector from inside a hot tub control panel
- Questions about bringing spices to New Zealand
- Loose bottom bracket on MTB
- Which type of license doesn't require attribution in Github projects?
- What is this movie where a woman is attacked and possessed by a worm
- Counting Letters in a String
- Old cartoon TV show (on DVD) about soccer ball-shaped characters that live in outer space or on an alien planet
- What would be the advantage of launching an UN-led inquiry over the Nord Stream sabotage?
- What is the point of Thrower's Bandolier?
- What video game is Charlie playing in Poker Face S01E07?
- Is it bad that your characters don't have distinct voices or mannerisms?
- What kind of wall is this and how can I repair it?
- Why are all monasteries human?
- Manhwa where female protagonist is transmigrated to a game she plays once she obtains certain amount of diamonds
Your privacy
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

Java Guides
Search this blog, jackson - list, set and map serialization and deserialization in java examples, table of contents.
- Using Jackson API for List Serialization
- Using Jackson API for Set Serialization
- Using Jackson API for Map Serialization
- Using Jackson API for List Deserialization
- Using Jackson API for Set Deserialization
- Using Jackson API for Map Deserialization
Dependencies
- jackson-annotations-2.9.8.jar
- jackson-core-2.9.8.jar
- jackson-databind-2.9.8.jar
1. Using Jackson API for List Serialization
Jacksonlisttojson, 2. using jackson api for set serialization, jacksonsettojson.java, 3. using jackson api for map serialization, jacksonmaptojson.java, 4. using jackson api for list deserialization, jacksonjsontolist.java, 5. using jackson api for set deserialization, jacksonjsontoset.java, 6. using jackson api for map deserialization, jacksonjsontomap.java, related articles.
- Jackson - Convert Java Object to/from JSON Example (popular)
- Jackson - List, Set, and Map Serialization and Deserialization in Java Examples
- Change Field Name in JSON using Jackson (popular)
- How to Read / Write JSON Using Jackson JsonParser and JsonGenerator
- Jackson - Enable Pretty Print JSON Output (popular)
- Jackson @JsonPropertyOrder Example
- Jackson - Ignore Fields or Properties on Serialization
- Jackson @JsonIgnore, @JsonIgnoreProperties and @JsonIgnoreType (popular)
- Jackson Ignore Null and Empty Fields on Serialization (popular)
- Jackson @JsonInclude Example
GitHub Repository
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
Post a Comment
Copyright © 2018 - 2022 Java Guides All rights reversed | Privacy Policy | Contact | About Me | YouTube | GitHub
- Books Get Your Hands Dirty on Clean Architecture Stratospheric
- Contribute Become an Author Writing Guide Author Workflow Author Payment
- Services Book me Advertise
- Categories Spring Boot Java Node Kotlin AWS Software Craft Simplify! Meta Book Reviews
All You Need To Know About JSON Parsing With Jackson
- July 15, 2022
Most of the web today exchanges data in JSON format. Web servers, web and mobile applications, even IoT devices all talk with each other using JSON. Therefore, an easy and flexible way of handling JSON is essential for any software to survive in today’s world.
Example Code
What is json.
JSON stands for “JavaScript Object Notation”, it’s a text-based format for representing structured data based on JavaScript object syntax. Its dynamic and simple format made it extremely popular. In its essence, it follows a key-value map model allowing nested objects and arrays:
What is Jackson?
Jackson is mainly known as a library that converts JSON strings and Plain Old Java Objects (POJOs). It also supports many other data formats such as CSV, YML, and XML.
Jackson is preferred by many people because of its maturity (13 years old) and its excellent integration with popular frameworks, such as Spring. Moreover, it’s an open-source project that is actively developed and maintained by a wide community.
Under the hood, Jackson has three core packages Streaming , Databind , and Annotations . With those, Jackson offers us three ways to handle JSON-POJO conversion:
Streaming API
It’s the fastest approach of the three and the one with the least overhead. It reads and writes JSON content as discrete events. The API provides a JsonParser that reads JSON into POJOs and a JsonGenerator that writes POJOs into JSON.
The Tree Model creates an in-memory tree representation of the JSON document. An ObjectMapper is responsible for building a tree of JsonNode nodes. It is the most flexible approach as it allows us to traverse the node tree when the JSON document doesn’t map well to a POJO.
Data Binding
It allows us to do conversion between POJOs and JSON documents using property accessors or using annotations. It offers two types of binding:
Simple Data Binding which converts JSON to and from Java Maps, Lists, Strings, Numbers, Booleans, and null objects.
Full Data Binding which Converts JSON to and from any Java class.
ObjectMapper
ObjectMapper is the most commonly used part of the Jackson library as it’s the easiest way to convert between POJOs and JSON. It lives in com.fasterxml.jackson.databind .
The readValue() method is used to parse (deserialize) JSON from a String, Stream, or File into POJOs.
On the other hand, the writeValue() method is used to turn POJOs into JSON (serialize).
The way ObjectMapper works to figure out which JSON field maps to which POJO field is by matching the names of the JSON fields to the names of the getter and setter methods in the POJO .
That is done by removing the “get” and “set” parts of the names of the getter and setter methods and converting the first character of the remaining method name to lowercase.
For example, say we have a JSON field called name , ObjectMapper will match it with the getter getName() and the setter setName() in the POJO.
ObjectMapper is configurable and we can customize it to our needs either directly from the ObjectMapper instance or by using Jackson annotations as we will see later.
Maven Dependencies
Before we start looking at code, we need to add Jackson Maven dependency jackson-databind which in turn transitively adds jackson-annotations and jackson-core
We are also using Lombok to handle the boilerplate code for getters, setters, and constructors.
Basic JSON Serialization and Deserialization with Jackson
Let’s go through Jackson’s most important use-cases with code examples.
Basic POJO / JSON Conversion Using ObjectMapper
Let’s start by introducing a simple POJO called Employee:
Let’s start by turning a POJO to a JSON string:
We should see this as output:
Now, Let’s see convert a JSON string to an Employee object using the ObjectMapper .
The ObjectMapper also offers a rich API to read JSON from different sources into different formats, let’s check the most important ones.
Creating a POJO from a JSON file
This is done using the readValue() method.
JSON file under test resources employee.json :
Creating a POJO from a Byte Array of JSON
Creating a list of pojos from json.
Sometimes the JSON document isn’t an object, but a list of objects. Let’s see how we can read that.
employeeList.json :
Creating a Map from JSON
We can choose to parse the JSON to a Java Map , which is very convenient if we don’t know what to expect from the JSON file we are trying to parse. ObjectMapper will turn the name of each variable in the JSON to a Map key and the value of that variable to the value of that key.
Ignore Unknown JSON fields
Sometimes the JSON we expect might have some extra fields that are not defined in our POJO. The default behavior for Jackson is to throw a UnrecognizedPropertyException exception in such cases. We can, however, tell Jackson not to stress out about unknown fields and simply ignore them. This is done by configuring ObjectMapper’s FAIL_ON_UNKNOWN_PROPERTIES to false.
employeeWithUnknownProperties.json :
Working with Dates in Jackson
Date conversions can be tricky as they can be represented with many formats and levels of specification (seconds, milliseconds, etc..).
Date to JSON
Before talking about Jackson and Date conversion, we need to talk about the new Date API provided by Java 8. It was introduced to address the shortcomings of the older java.util.Date and java.util.Calendar . We are mainly interested in using the LocalDate class which offers a powerful way to express date and time.
To do that, we need to add an extra module to Jackson so that it can handle LocalDate .
Then we need to tell the ObjectMapper to look for and register the new module we’ve just added.
The default behavior for Jackson then is to show the date as [yyyy-MM-dd] So, the output would be {"id":1,"date":[1900,2,1]}
We can, however, tell Jackson what format we want the date to be. This can be done using the @JsonFormat annotation
This should output {"id":1,"date":"01/01/2023"} .
JSON to Date
We can use the same configuration above to read a JSON field into a date.
order.json :
Jackson Annotations
Annotations in Jackson play a major role in customizing how the JSON/POJO conversion process takes place. We have seen an example of it with the date conversion where we used the @JsonFormat annotation. Annotations mainly affect how the data is read, written or even both. Let’s explore some of those annotations based on their categories.
Read Annotations
They affect how Jackson converts JSON into POJOs.
@JsonSetter
This is useful when we want to match a field in the JSON string to a field in the POJO where their names don’t match.
@JsonAnySetter
This annotation is useful for cases where the JSON contains some fields that are not declared in the POJO. It is used with a setter method that is called for every unrecognized field.
carUnrecognized.json file:
Write Annotations
They affect how Jackson converts POJOs into JSON.
@JsonGetter
This is useful when we want to map a POJOs field to a JSON field using a different name. For example, say we have this Cat class with the field name , but we want its JSON name to be catName .
This will output
@JsonAnyGetter
This annotation allows us to treat a Map object as a source of JSON properties. Say we have this map as a field in the Cat class
Then this will output
Read/Write Annotations
Those annotations affect both reading and writing a JSON.
@JsonIgnore
The annotated filed is ignored while both writing and reading JSON.
This will print out {"name":"Max"}
The same applies to reading into a POJO as well.
Say we have this dog.json file:
Jackson has many more useful annotations that give us more control over the serialization/deserialization process. The full list of them can be found on Jackson’s Github repository .
Jackson is one of the most powerful and popular libraries for JSON processing in Java.
Jackson consists of three main modules Streaming API , Tree Model , and Data Binding .
Jackson provides an ObjectMapper which is highly configurable to suit our needs through setting its properties and also using annotations.
You can find all the example code in the GitHub repo .
Abdulcelil Cercenazi
Software developer and craftsman. Loves working with Java | Spring | Docker. Always looking for new adventures
Recent Posts
Getting started with spring security and spring boot.
- February 28, 2023
Spring Security is a framework that helps secure enterprise applications. By integrating with Spring MVC, Spring Webflux or Spring Boot, we can create a powerful and highly customizable authentication and access-control framework.
Demystifying Transactions and Exceptions with Spring
- January 31, 2023
One of the most convincing justifications for using the Spring Framework is its extensive transaction support. For transaction management, the Spring Framework offers a stable abstraction.
JUnit 5 Parameterized Tests
- January 29, 2023
If you’re reading this article, it means you’re already well-versed with JUnit. Let me give you a summary of JUnit - In software development, we developers write code which does something simple as designing a person’s profile or as complex as making a payment (in a banking system).

IMAGES
VIDEO
COMMENTS
Andrew Jackson’s most significant failure as president was to allow the state of Georgia to evict the Cherokee Indians from their indigenous lands. Jackson vetoed the charter for the Second Bank of the United States, taking the money out an...
In total, there are 1,824 pages in the “Percy Jackson” book series. Written by Rick Riordan, the series includes five books: “The Lightning Thief,” “The Sea of Monsters,” “The Titan’s Curse,” “The Battle of the Labyrinth” and “The Last Olym...
Andrew Jackson’s spoils system was a deliberate policy after he became president to remove federal employees he considered to be political opponents and replace them with his own supporters.
Jackson Annotations · The @JsonGetter annotation is an alternative to the @JsonProperty annotation, which marks a method as a getter method. · the
Core annotations (annotations that only depend on jackson-core) for Jackson data processor - GitHub - FasterXML/jackson-annotations: Core annotations
@JsonTypeName is used to set type names to be used for annotated class. Example - @JsonTypeName. import java.io.IOException;
Jackson Serialization Annotations · @JsonValue. @JsonValue · @JsonInclude. @JsonInclude · @JsonGetter. @JsonGetter · @JsonAnyGetter. @JsonAnyGetter · @
Jackson Annotations For Java Application ; Annotation 1: @JsonAnyGetter ; Annotation 2: @JsonGetter ; Annotation 4: @JsonRawValue ; Annotation 5: @
com.fasterxml. · jackson-annotations. jackson-annotations jackson-core jackson-databind · 2.14.2.
Package com.fasterxml.jackson.annotation ; JsonIgnoreProperties.Value. Helper class used to contain information from a single JsonIgnoreProperties annotation, as
Jackson Annotations ; Read + Write Annotations. @JsonIgnore; @JsonIgnoreProperties; @JsonIgnoreType; @JsonAutoDetect ; Read Annotations. @
@JsonRootName(value = "user") public class User { @JsonProperty("id") private long id; @JsonProperty("diets") private List<Diet> diets = new
jackson-databind-2.9.8.jar. Always use the latest versions on the Maven central repository for Jackson databind. 1. Using Jackson API for List Serialization.
It lives in com.fasterxml.jackson.databind . ... Sometimes the JSON document isn't an object, but a list of objects.