
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Importance of @JsonRootName annotation using Jackson in Java?
In Java, Jackson is a library that is used to convert JSON to Java objects and vice versa. Jackson Annotations are used during serialization and deserialization. We use annotations with a particular field or method that is declared in Java.
So, Annotations make the JSON output clearer as we required. In this Article, we will learn about one of its annotations @JsonRootName.
@JsonRootName Annotatation
The @JsonRootName annotation is a Jackson annotation that is used on a class if we want to do wrapping in our JSON attributes. It is a class-level annotation.
It wraps the object to be serialized with a top-level element. To make use of this annotation, you need to specify the name to be used as the wrapper element by passing it as a parameter, and you will have to enable wrapping in the ObjectMapper you are using.
For this, we can use the "WRAP_ROOT_VALUE" feature of the SerializationFeature enum that can be enabled to make the root value wrapped within a single property JSON object, where the key(wrapper element) is the root name. By default, Jackson does not wrap values.
Example
This program serializes an Employee object into JSON with a root wrapper named "user", using Jackson's @JsonRootName annotation. The output will be a JSON string with "user" as the root element encapsulating the employee data.
import com.fasterxml.jackson.annotation.JsonRootName; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.SerializationFeature; public class JsonRootNameAnnotationTest { public static void main(String args[]) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); String jsonString = mapper.enable(SerializationFeature.WRAP_ROOT_VALUE).writeValueAsString(new Employee()); System.out.println(jsonString); } } @JsonRootName(value = "user") class Employee { public int empId = 125; public String empName = "Raja Ramesh"; }
Following is the output of the above code -
{"user":{"empId":125,"empName":"Raja Ramesh"}}