Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Khi nào sử dụng @JsonValue trong Jackson (Java)

Annotation @JsonValue áp dụng ở **method level** để tùy chỉnh cách một object được serialize thành JSON string. Thay vì override toString(), ta định nghĩa method trả về representation mong muốn.

Cú pháp

@Target({ANNOTATION_TYPE, METHOD, FIELD})
@Retention(RUNTIME)
public @interface JsonValue

Ví dụ minh họa

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonValue;
import com.fasterxml.jackson.databind.ObjectMapper;

public class JsonValueTest {
    public static void main(String[] args) throws Exception {
        ObjectMapper mapper = new ObjectMapper();
        String json = mapper.writeValueAsString(new Student());
        System.out.println(json);
    }
}

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]"

Toàn bộ object được serialize thành **một JSON string duy nhất** do method toJson() trả về.

Khi nào dùng @JsonValue?

  • Muốn serialize object thành **giá trị đơn giản** (String, Number) thay vì JSON object.
  • Enum serialization: trả về code/label thay vì tên enum.
  • Wrapper class (Value Object) muốn hiển thị giá trị cốt lõi.
  • Tương thích ngược với hệ thống legacy expect string format cụ thể.

Lưu ý

  • Chỉ **một method** được annotate @JsonValue trong một class.
  • Method phải public, non-static, không tham số.
  • Return type có thể là bất kỳ type nào Jackson hỗ trợ serialize.
  • Deserialize: cần @JsonCreator hoặc custom deserializer để parse ngược.