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

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

王林
Release: 2023-09-01 22:05:05
forward
1169 people have browsed it

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>
Copy after login

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;;
   }
}
Copy after login

Output

<strong>"Sai Adithya,115,Student[studentId = 115, studentName = Sai Adithya]"</strong>
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template