Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to ignore the multiple properties of a JSON object in Java?
The @JsonIgnoreProperties Jackson annotation can be used to specify a list of properties or fields of a class to ignore. The @JsonIgnoreProperties annotation can be placed above the class declaration instead of above the individual properties or fields to ignore.
Syntax
@Target(value={ANNOTATION_TYPE,TYPE,METHOD,CONSTRUCTOR,FIELD})
@Retention(value=RUNTIME)
public @interface JsonIgnoreProperties
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"})
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;
}
@Override
public String toString() {
return "Customer [id=" + id + ", name=" + name + ", address=" + address + "]";
}
}
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]Advertisements