Home > Java > javaTutorial > How to ignore multiple properties of JSON object in Java?

How to ignore multiple properties of JSON object in Java?

王林
Release: 2023-09-18 22:29:02
forward
708 people have browsed it

How to ignore multiple properties of JSON object in Java?

@JsonIgnorePropertiesThe Jackson annotation can be used to specify a property list or field for a class to ignore. @JsonIgnoreProperties annotation Can be placed before a class declaration instead of before an individual property or field to be ignored.

Syntax

@Target(value={ANNOTATION_TYPE,TYPE,METHOD,CONSTRUCTOR,FIELD})
@Retention(value=RUNTIME)
public @interface JsonIgnoreProperties
Copy after login

Example

import java.io.*;
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.databind.*;
public class JsonIgnorePropertiesTest {
   public static void main(String[] args) throws IOException {
      Customer customer = new Customer("120", "Ravi", "Hyderabad");
      System.out.println(customer);
      ObjectMapper mapper = new ObjectMapper();
      String jsonString = mapper.writeValueAsString(customer);
      System.out.println("JSON: " + jsonString);
      System.out.println("---------");
      jsonString = "{\"id\":\"130\",\"name\":\"Rahul\", \"address\":\"Mumbai\"}";
      System.out.println("JSON: " + jsonString);
      customer = mapper.readValue(jsonString, Customer.class);
      System.out.println(customer);
   }
}
// Customer class
@JsonIgnoreProperties({"id", "address"}) <strong>
</strong>class Customer {
   private String id;
   private String name;
   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;
   }
<strong>   </strong>@Override
   public String toString() {
      return "Customer [id=" + id + ", name=" + name + ", address=" + address + "]";
   }
}
Copy after login

Output

Customer [id=120, name=Ravi, address=Hyderabad]
JSON: {"name":"Ravi"}
---------
JSON: {"id":"130","name":"Rahul", "address":"Mumbai"}
Customer [id=null, name=Rahul, address=null]
Copy after login

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

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template