What is the use of @JsonRawValue annotation using Jackson API in Java?

JavaJSONObject Oriented ProgrammingProgramming

The @JsonRawValue annotation can be used for both methods and fields to serialize field or property as declared. For instance, if we have a String field in our Java class, the JSON value is enclosed within quotes (“ "). But when we annotate the field with @JsonRawValue annotation, Jackson library omits the quotes.

Syntax

@Target(value={ANNOTATION_TYPE,METHOD,FIELD})
@Retention(value=RUNTIME)
public @interface JsonRawValue

In the below example, the empAddress field is a JSON string. This JSON string serialized as a part of the final JSON string of Employee object.

Example

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"}
}
raja
Published on 08-Nov-2019 11:44:45
Advertisements