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

Tầm quan trọng của chú thích Jackson @JsonInclude trong Java?

Jackson @JsonInclude chú thích có thể được sử dụng để loại trừ các thuộc tính hoặc các trường của một lớp trong các điều kiện nhất định và nó có thể được xác định bằng cách sử dụng JsonInclude.Include enum . JsonInclude.Include enum chứa một số hằng số như " ALWAYS", "NON_DEFAULT", "NON_EMPTY" và "NON_NULL" để xác định xem có loại trừ thuộc tính (trường) hay không.

Cú pháp

public static enum JsonInclude.Include extends Enum<JSonInclude.Include>

Ví dụ

import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
import java.io.*;
public class JsonIncludeTest {
   public static void main(String args[]) throws IOException {
      ObjectMapper objectMapper = new ObjectMapper();
      Employee emp = new Employee();
      String jsonString = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(emp);
      System.out.println(jsonString);
   }
}
// Employee class
@JsonInclude(JsonInclude.Include.NON_EMPTY)
class Employee {
   public int empId = 115;
   public String empName = null;
   @Override
   public String toString() {
      return "Employee{" +
             "empId=" + empId +
             ", empName='" + empName + '\'' +
             '}';
   }
}

Đầu ra

{
   "empId" : 115
}