在 Java 中使用 Jackson 時,何時使用 @JsonValue 註解?\n
@JsonValue 註解在方法級別很有用。我們可以使用此註解從 Java 物件生成 JSON 字串。如果我們想列印序列化物件,則覆蓋 toString() 方法。但使用 @JsonValue 註解,我們可以定義序列化 Java 物件的方法。
語法
@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]"
廣告