- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- 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?
The @JsonRootName annotation can be used to wrap an object to serialize with a top-level element. We can pass the name as a parameter to @JsonRootName annotation. We can use the "WRAP_ROOT_VALUE" feature of SerializationFeature enum that can be enabled to make root value wrapped within a single property JSON object where the key is a root name.
Example
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"; }
Output
{"user":{"empId":125,"empName":"Raja Ramesh"}}
Advertisements