@JsonValue 주석 메서드 수준에서 유용합니다. 이 주석을 사용하여 Java 객체에서 JSON 문자열을 생성할 수 있습니다. 직렬화된 객체를 인쇄하려면 toString()을 재정의합니다. 방법. 그러나 @JsonValue 주석을 사용하면 , 우리는 자바 객체가 직렬화되는 방식을 정의할 수 있습니다.
구문
@Target(value={ANNOTATION_TYPE,METHOD,FIELD})
@Retention(value=RUNTIME)
public @interface JsonValue 예
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 +
']';
}
} 출력
"Sai Adithya,115,Student[studentId = 115, studentName = Sai Adithya]"