Java 中 Jackson @JsonInclude 注释的重要性?

javajsonobject oriented programmingprogramming

Jackson @JsonInclude 注释可用于在特定条件下排除类的属性字段,并且可以使用 JsonInclude.Include枚举进行定义。JsonInclude.Include枚举包含一些常量,如"ALWAYS  ...

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

示例

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 + '\'' +
             '}';
   }
}

输出

{
   "empId" : 115
}

相关文章