When to use @JsonValue annotation using Jackson in Java?


The @JsonValue annotation is useful at the method level. We can use this annotation to generate a JSON string from java object. If we want to print a serialized object then override the toString() method. But using @JsonValue annotation, we can define a way in which java object is serialized.

Syntax

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

Example

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.io.IOException;
public class JsonValueAnnotationTest {
   public static void main(String args[]) throws Exception {
      ObjectMapper mapper = new ObjectMapper();
      String jsonString = mapper.writeValueAsString(new Student());
      System.out.println(jsonString);
   }
}
// Student class
class Student {
   @JsonProperty
   private int studentId = 115;
   @JsonProperty
   private String studentName = "Sai Adithya";
   @JsonValue
   public String toJson() {
      return this.studentName + "," + this.studentId + "," + this.toString();
   }
   @Override
   public String toString() {
      return "Student[" +
            "studentId = " + studentId +
      ", studentName = " + studentName +
      ']';
   }
}

Output

"Sai Adithya,115,Student[studentId = 115, studentName = Sai Adithya]"

Updated on: 19-Feb-2020

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements