@JsonValue annotation is useful at the method level. We can use this annotation to generate JSON string from java object. If we want to print the serialized object, then override the toString() method. But using the @JsonValue annotation, we can define how java objects are serialized.
<strong>@Target(value={ANNOTATION_TYPE,METHOD,FIELD}) @Retention(value=RUNTIME) public @interface JsonValue</strong>
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 { <strong>ObjectMapper </strong>mapper = new <strong>ObjectMapper()</strong>; String jsonString = mapper.<strong>writeValueAsString</strong>(new Student()); System.out.println(jsonString); } } <strong>// Student class</strong> class Student { <strong>@JsonProperty</strong> private int studentId = 115; <strong> @JsonProperty</strong> private String studentName = "Sai Adithya"; <strong>@JsonValue</strong> public String <strong>toJson</strong>() { return this.studentName + "," + this.studentId + "," + this.toString(); } <strong>@Override</strong> public String toString() { return "Student[" + "studentId = " + studentId + ", studentName = " + studentName + ']'; } }
<strong>"Sai Adithya,115,Student[studentId = 115, studentName = Sai Adithya]"</strong>
The above is the detailed content of When to use @JsonValue annotation when using Jackson in Java?. For more information, please follow other related articles on the PHP Chinese website!