Chú thích @JsonValue hữu ích ở cấp độ phương pháp. Chúng ta có thể sử dụng chú thích này để tạo chuỗi JSON từ đối tượng java. Nếu chúng ta muốn in một đối tượng được tuần tự hóa thì hãy ghi đè toString () phương pháp. Nhưng sử dụng chú thích @JsonValue , chúng ta có thể xác định cách thức mà đối tượng java được tuần tự hóa.
Cú pháp
@Target(value={ANNOTATION_TYPE,METHOD,FIELD})
@Retention(value=RUNTIME)
public @interface JsonValue Ví dụ
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 +
']';
}
} Đầu ra
"Sai Adithya,115,Student[studentId = 115, studentName = Sai Adithya]"