The JsonView หมายเหตุ สามารถใช้เพื่อรวม/ยกเว้นคุณสมบัติในระหว่างกระบวนการทำให้เป็นอนุกรมและดีซีเรียลไลซ์เซชันแบบไดนามิก เราจำเป็นต้องกำหนดค่า ObjectMapper เพื่อรวมประเภทของมุมมองที่ใช้สำหรับการเขียน JSON จากวัตถุ Java โดยใช้ writerWithView() วิธีการ
ไวยากรณ์
@Target(value={ANNOTATION_TYPE,METHOD,FIELD})
@Retention(value=RUNTIME)
public @interface JsonView ตัวอย่าง
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonView;
import com.fasterxml.jackson.core.JsonProcessingException;
public class JsonViewAnnotationTest {
public static void main(String args[]) throws JsonProcessingException {
ObjectMapper objectMapper = new ObjectMapper();
String jsonString = objectMapper.writerWithView(Views.Public.class).writeValueAsString(new Person());
String jsonStringInternal = objectMapper.writerWithView(Views.Internal.class).writeValueAsString(new Person());
System.out.println(jsonString);
System.out.println(jsonStringInternal);
}
}
// Person class
class Person {
@JsonView(Views.Public.class)
public long personId = 115;
@JsonView(Views.Public.class)
public String personName = "Raja Ramesh";
@JsonView(Views.Internal.class)
public String gender = "male";
@Override
public String toString() {
return "Person{" +
"personId=" + personId +
", personName='" + personName + '\'' +
", gender='" + gender + '\'' +
'}';
}
}
class Views {
static class Public {}
static class Internal extends Public {}
} ผลลัพธ์
{"personId":115,"personName":"Raja Ramesh"}
{"personId":115,"personName":"Raja Ramesh","gender":"male"}