
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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]"
- Related Questions & Answers
- When to use @ConstructorProperties annotation with Jackson in Java?
- What is the use of @JacksonInject annotation using Jackson in Java?
- When to use @JsonAutoDetect annotation in Java?
- Importance of @JsonRootName annotation using Jackson in Java?
- Importance of @JsonView annotation using Jackson in Java?
- Importance of @JsonIdentityInfo annotation using Jackson in Java?
- Importance of @JsonUnwrapped annotation using Jackson in Java?
- What is the use of @JsonRawValue annotation using Jackson API in Java?
- When to use @JsonManagedReference and @JsonBackReference annotations using Jackson in Java?
- Importance of the Jackson @JsonInclude annotation in Java?
- What to use @SerializedName annotation using Gson in Java?
- How to use @Until annotation using the Gson library in Java?
- How can we use @Since annotation using Gson in Java?
- JSON Schema Support using Jackson in Java?
- When to use an abstract class and when to use an interface in Java?
Advertisements