首页 >Java >java教程 >如何在Java中使用Jackson库忽略JSON对象的字段?

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

PHPz
PHPz转载
2023-09-12 09:41:071499浏览

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

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 class<strong>
</strong>class Customer {
   private String id;
   private String name;
<strong>  </strong> @JsonIgnore<strong>
</strong>   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]

以上是如何在Java中使用Jackson库忽略JSON对象的字段?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除