Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

วิธีเพิกเฉยต่อคลาสระหว่างการทำซีเรียลไลซ์ด้วย Jackson ใน Java

Annotation @JsonIgnoreType ของ Jackson ใช้สำหรับ เพิกเฉยต่อ คลาส ระหว่างกระบวนการ ซีเรียลไลซ์ (serialization) และสามารถทำเครื่องหมายให้ คุณสมบัติ (properties) หรือ ฟิลด์ (fields) ทั้งหมดของคลาสถูกเพิกเฉยขณะ ทำซีเรียลไลซ์ (serializing) และ ถอดรหัส (deserializing) อ็อบเจกต์ JSON

ไวยากรณ์

@Target(value={ANNOTATION_TYPE,TYPE})
@Retention(value=RUNTIME)
public @interface JsonIgnoreType

ตัวอย่างโค้ด

import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import java.io.*;

public class JsonIgnoreTypeTest {
    public static void main(String args[]) throws IOException {
        Employee emp = new Employee();
        ObjectMapper mapper = new ObjectMapper();
        String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(emp);
        System.out.println(jsonString);
    }
}

// คลาส Employee
class Employee {
    @JsonIgnoreType
    public static class Address {
        public String firstLine = null;
        public String secondLine = null;
        public String thirdLine = null;
        
        @Override
        public String toString() {
            return "Address{" +
                "firstLine='" + firstLine + '\'' +
                ", secondLine='" + secondLine + '\'' +
                ", thirdLine='" + thirdLine + '\'' +
                '}';
        }
    } // จบคลาส Address
    
    public long empId = 115;
    public String empName = "Raja Ramesh";
    public Address empAddress = new Address();
    
    @Override
    public String toString() {
        return "Employee{" +
            "empId=" + empId +
            ", empName='" + empName + '\'' +
            ", empAddress=" + empAddress +
            '}';
    }
}

ผลลัพธ์

{
    "empId" : 115,
    "empName" : "Raja Ramesh"
}