如何使用 Java 中的 Jackson 库忽略 JSON 对象的字段?\

javajsonobject oriented programmingprogramming

Jackson @JsonIgnore 注释可用于忽略 Java 对象的某个属性字段。在将 JSON 读入 Java 对象时以及在将 Java 对象写入 JSON 时都可以忽略该属性。我们可以使用 ObjectMapper 类的 readValue()writeValueAsString() 方法将 JSON 读入 Java 对象以及将 Java 对象写入 JSON。

语法

@Target(value={ANNOTATION_TYPE,METHOD,CONSTRUCTOR,FIELD})
@Retention(value=RUNTIME)
public @interface JsonIgnore

示例

import java.io.*;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
public class JsonIgnoreTest {
   public static void main(String[] args) throws IOException {
      Customer customer = new Customer("110", "Surya Kiran", "Chennai");
      System.out.println(customer);
      ObjectMapper mapper = new ObjectMapper();
      String jsonString = mapper.writeValueAsString(customer);
      System.out.println("JSON: " + jsonString);
      System.out.println("---------");
      jsonString = "{\"id\":\"120\",\"name\":\"Devaraj\", \"address\":\"Banglore\"}";
      System.out.println("JSON: " + jsonString);
      customer = mapper.readValue(jsonString, Customer.class);
      System.out.println(customer);
   }
}
// Customer classclass Customer {
   private String id;
   private String name;
   @JsonIgnore   private String address;
   public Customer() {
   }
   public Customer(String id, String name, String address) {
      this.id = id;
      this.name = name;
      this.address = address;
   }
   public String getId() {
      return id;
   }
   public String getName() {
      return name;
   }
   public String getAddress() {
      return address;
   }
   @Override
   public String toString() {
      return "Customer [id=" + id + ", name=" + name + ", address=" + address + "]";
   }
}

输出

Customer [id=110, name=Surya Kiran, address=Chennai]
JSON: {"id":"110","name":"Surya Kiran"}
---------
JSON: {"id":"120","name":"Devaraj", "address":"Banglore"}
Customer [id=120, name=Devaraj, address=null]

相关文章