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

Làm thế nào để bỏ qua một lớp trong quá trình tuần tự hóa bằng cách sử dụng Jackson trong Java?


Jackson @JsonIgnoreType chú thích có thể được sử dụng để bỏ qua a lớp học trong quá trình tuần tự hóa xử lý và nó có thể đánh dấu tất cả các thuộc tính hoặc trường của một lớp sẽ bị bỏ qua trong khi tuần tự hóa deserializing một đối tượng JSON.

Cú pháp

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

Ví dụ

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
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 + '\'' +
                '}';
      }
   } // end of Address class
   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 +
             '}';
   }
}

Đầu ra

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