คำอธิบายประกอบ @JsonRawValue ใช้ได้ทั้งเมธอดและฟิลด์ เพื่อ serialize field/property ตามที่ประกาศไว้โดยตรง ตัวอย่างเช่น ถ้ามี String field ใน Java class ค่า JSON จะถูกล้อมรอบด้วย double quotes (" ") แต่เมื่อ annotate ด้วย @JsonRawValue Jackson library จะละเว้น quotes นั้น
Syntax
@Target(value={ANNOTATION_TYPE, METHOD, FIELD})
@Retention(value=RUNTIME)
public @interface JsonRawValue
ตัวอย่างการใช้งาน
import com.fasterxml.jackson.annotation.JsonRawValue;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
public class JsonRawValueAnnotationTest {
public static void main(String args[]) throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(new Employee());
System.out.println(jsonString);
}
}
// Employee class
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"}
}
คำอธิบาย
โดยไม่มี @JsonRawValue empAddress จะถูก serialize เป็น JSON string (มี escape quotes):
"empAddress" : "{\"doorNumber\": 1118, \"street\": \"IDPL Colony\", \"city\": \"Hyderabad\"}"
แต่ด้วย @JsonRawValue Jackson จะ treat ค่านี้เป็น raw JSON และ embed เข้าไปโดยตรง ทำให้ได้ nested object แทน string
กรณีการใช้งาน (Use Cases)
- เมื่อมี JSON string สำเร็จรูปอยู่ในฟิลด์แล้ว และต้องการ embed เข้าไปโดยตรง
- เมื่อ integrate กับระบบภายนอกที่ส่ง JSON string มา และต้องการรวมเข้าไปใน response
- เมื่อต้องการควบคุมการ serialize ส่วนหนึ่งของ object เอง (custom serialization สำหรับฟิลด์เฉพาะ)
- Performance optimization - หลีกเลี่ยงการ parse/unparse JSON ซ้ำ
ข้อควรระวัง
- JSON string ในฟิลด์ต้องเป็น valid JSON มิฉะนั้นจะทำให้ output invalid
- ไม่ควรใช้กับข้อมูลที่มาจาก user input โดยไม่ validate (security risk)
- ไม่ทำงานกับ deserialization (ต้องใช้ custom deserializer คู่กัน)
สรุป
@JsonRawValue เป็นเครื่องมือเฉพาะเจาะจงสำหรับ embed raw JSON ลงใน JSON output ควรใช้ด้วยความระมัดระวังและ validate input ให้ดี