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

Sử dụng @JsonRawValue trong Jackson (Java)

Annotation @JsonRawValue cho phép serialize field/property **nguyên vẹn** (raw) mà không escape quotes. Dùng khi field đã là JSON string hợp lệ và muốn nhúng trực tiếp vào JSON output.

Cú pháp

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

Ví dụ minh họa

import com.fasterxml.jackson.annotation.JsonRawValue;
import com.fasterxml.jackson.databind.ObjectMapper;

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

class Employee {
    public int empId = 115;
    public String empName = "Sai Chaitanya";
    
    @JsonRawValue
    public String empAddress = "{\"doorNumber\": 1118, \"street\": \"IDPL Colony\", \"city\": \"Hyderabad\"}";
}

Output

{
  "empId" : 115,
  "empName" : "Sai Chaitanya",
  "empAddress" : {"doorNumber": 1118, "street": "IDPL Colony", "city": "Hyderabad"}
}

Không có @JsonRawValue: "empAddress" : "{\\"doorNumber\\": 1118, ...}" (escaped string).

Khi nào dùng?

  • Nhúng JSON string đã có sẵn (từ DB, cache, external service) vào JSON response.
  • Performance: tránh parse rồi re-serialize object phức tạp.
  • Embed raw JSON từ column JSONB/JSON trong database (PostgreSQL, MySQL 5.7+).

⚠️ Cảnh báo bảo mật & rủi ro

  • Injection risk: Nếu raw JSON từ input không tin cậy → có thể inject field độc hại.
  • Invalid JSON: Nếu string không phải JSON hợp lệ → output bị corrupt.
  • Type safety: Mất type checking, validation của Jackson.

Best Practice

  • Chỉ dùng khi **bắt buộc** (performance critical, legacy integration).
  • Validate JSON string trước khi gán vào field (dùng JsonNode hoặc schema validation).
  • Ưu tiên model object bình thường + @JsonUnwrapped/@JsonProperty cho type-safe.