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

เมื่อไหร่ควรใช้ @JsonAutoDetect ใน Java

Annotation @JsonAutoDetect ใช้ที่ระดับคลาสเพื่อ ลบล้างการมองเห็น (visibility) ของคุณสมบัติของคลาสระหว่าง การทำซีเรียลไลซ์ (serialization) และ การถอดรหัส (deserialization) เราสามารถตั้งค่าการมองเห็นด้วยคุณสมบัติเช่น "creatorVisibility", "fieldVisibility", "getterVisibility", "setterVisibility" และ "isGetterVisibility" คลาส JsonAutoDetect กำหนด public static constants ที่คล้ายกับระดับการมองเห็นของคลาส Java เช่น "ANY", "DEFAULT", "NON_PRIVATE", "NONE", "PROTECTED_AND_PRIVATE" และ "PUBLIC_ONLY"

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

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

public class JsonAutoDetectTest {
    public static void main(String[] args) throws IOException {
        Address address = new Address("Madhapur", "Hyderabad", "Telangana");
        Name name = new Name("Raja", "Ramesh");
        Student student = new Student(address, name, true);
        
        ObjectMapper mapper = new ObjectMapper();
        String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(student);
        System.out.println("JSON: " + jsonString);
    }
}

// คลาส Address
class Address {
    private String firstLine;
    private String secondLine;
    private String thirdLine;
    
    public Address(String firstLine, String secondLine, String thirdLine) {
        this.firstLine = firstLine;
        this.secondLine = secondLine;
        this.thirdLine = thirdLine;
    }
    
    public String getFirstLine() { return firstLine; }
    public String getSecondLine() { return secondLine; }
    public String getThirdLine() { return thirdLine; }
}

// คลาส Name
class Name {
    private String firstName;
    private String secondName;
    
    public Name(String firstName, String secondName) {
        this.firstName = firstName;
        this.secondName = secondName;
    }
    
    public String getFirstName() { return firstName; }
    public String getSecondName() { return secondName; }
}

// คลาส Student
@JsonAutoDetect(fieldVisibility = JsonAutoDetect.Visibility.ANY)
class Student {
    private Address address;
    private Name name;
    private Boolean isActive;
    
    public Student(Address address, Name name, Boolean isActive) {
        this.address = address;
        this.name = name;
        this.isActive = isActive;
    }
}

ผลลัพธ์

{
    "address": {
        "firstLine": "Madhapur",
        "secondLine": "Hyderabad",
        "thirdLine": "Telangana"
    },
    "name": {
        "firstName": "Raja",
        "secondName": "Ramesh"
    },
    "isActive": true
}