Home >Java >javaTutorial >When to use @JsonValue annotation when using Jackson in Java?

When to use @JsonValue annotation when using Jackson in Java?

王林
王林forward
2023-09-01 22:05:051155browse

When to use @JsonValue annotation when using Jackson in Java?

@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.

Syntax

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

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 {
      <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 +
      &#39;]&#39;;
   }
}

Output

<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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete