
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
What is the use of @JsonRawValue annotation using Jackson API 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 to denote a particular field that is declared in Java as an instance variable, is a JsonProperty, and should be ignored. We can also use annotations with methods.
So, basically, Annotations make JSON output clearer as we required. In this Article, we will learn about one of its annotations is @JsonRawValue Annotation.
@JsonRawValue
This annotation can be used for methods and fields. The @JsonRawValue annotation is used to serialize methods or fields as it is they are declared. As we know, JSON wraps string values in quotes(" "). But when we use this annotation with a field or method, the value we will get will be in its raw form.
For example, if we have a String field in our Java class having a value like- Java, the JSON value is enclosed within quotes (" "). But when we annotate the field with @JsonRawValue annotation, the Jackson library omits the quotes.
This annotation is useful when we are handling preformatted JSON. So, during serialization, it will be treated as plain text.
Example
The following example serializes an Employee object into JSON using Jackson, ensuring that the empAddress field remains as raw JSON, instead of a regular string.
import com.fasterxml.jackson.annotation.JsonRawValue; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.core.JsonProcessingException; public class JsonRawValueAnnotationTest { public static void main(String args[]) throws JsonProcessingException { ObjectMapper mapper = new ObjectMapper(); String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(new Employee()); System.out.println(jsonString); } } // Employee class class Employee { public int empId = 115; public String empName = "Sai Chaitanya"; @JsonRawValue public String empAddress = "{"doorNumber": 1118, "street": "IDPL Colony", " + ""city": "Hyderabad"}"; }
Output
{ "empId" : 115, "empName" : "Sai Chaitanya", "empAddress" : {"doorNumber": 1118, "street": "IDPL Colony", "city": "Hyderabad"} }