Home >Java >javaTutorial >How to ignore fields of JSON object using Jackson library in Java?

How to ignore fields of JSON object using Jackson library in Java?

PHPz
PHPzforward
2023-09-12 09:41:071501browse

How to ignore fields of JSON object using Jackson library in Java?

Jackson @JsonIgnore annotation can be used to ignore a certain attribute or field A Java object. This property can be ignored when reading JSON into Java objects and when writing Java objects into JSON. We can read JSON into Java objects and write Java objects into JSON using the readValue() and writeValueAsString() methods of the ObjectMapper class.

Syntax

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

Example

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 + "]";
   }
}

Output

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]

The above is the detailed content of How to ignore fields of JSON object using Jackson library in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete