Computer >> Máy Tính >  >> Lập trình >> Java

Việc sử dụng chú thích @JsonRawValue bằng cách sử dụng API Jackson trong Java là gì?


@JsonRawValue chú thích có thể được sử dụng cho cả phương thức và trường để tuần tự hóa trường hoặc thuộc tính như đã khai báo. Ví dụ:nếu chúng ta có trường Chuỗi trong lớp Java của mình, giá trị JSON được đặt trong dấu ngoặc kép ( “" ). Nhưng khi chúng tôi chú thích trường bằng @JsonRawValue chú thích, thư viện Jackson bỏ qua phần trích dẫn.

Cú pháp

 @Target (value ={ANNOTATION_TYPE, METHOD, FIELD}) @ Giữ chân (value =RUNTIME) public @interface JsonRawValue 

Trong ví dụ dưới đây, empAddress trường là một chuỗi JSON. Chuỗi JSON này được tuần tự hóa như một phần của chuỗi JSON cuối cùng của Nhân viên đối tượng.

Ví dụ

 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]) ném JsonProcessingException {ObjectMapper mapper =new ObjectMapper (); String jsonString =mapper.writerWithDefaultPrettyPrinter (). WriteValueAsString (new Employee ()); System.out.println (jsonString); }} // Lớp nhân viên Employee {public int empId =115; public String empName ="Sai Chaitanya"; @JsonRawValue public String empAddress ="{\" doorNumber \ ":1118, \" street \ ":\" IDPL Colony \ "," + "\" city \ ":\" Hyderabad \ "}";} 

Đầu ra

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