@JsonIgnore
annotation is used to ignore fields from json serialization.
In
the below snippet, I am ignoring hobbies.
public
class Employee {
@JsonProperty("EMPLOYEE_DD")
private int id;
@JsonProperty("EMPLOYEE_FIRST_NAME")
private String firstName;
@JsonProperty("EMPLOYEE_LAST_NAME")
private String lastName;
@JsonIgnore
private List<String> hobbies =
new ArrayList<>();
}
package com.sample.model; import java.util.ArrayList; import java.util.List; import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonPropertyOrder; @JsonInclude(JsonInclude.Include.NON_NULL) @JsonPropertyOrder({ "firstName", "lastName", "hobbies", "id" }) public class Employee { @JsonProperty("EMPLOYEE_DD") private int id; @JsonProperty("EMPLOYEE_FIRST_NAME") private String firstName; @JsonProperty("EMPLOYEE_LAST_NAME") private String lastName; @JsonIgnore private List<String> hobbies = new ArrayList<>(); public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public List<String> getHobbies() { return hobbies; } public void setHobbies(List<String> hobbies) { this.hobbies = hobbies; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("Employee [id=").append(id).append(", firstName=").append(firstName).append(", lastName=") .append(lastName).append(", hobbies=").append(hobbies).append("]"); return builder.toString(); } }
App.java
package com.sample.app; import java.io.IOException; import com.fasterxml.jackson.core.JsonGenerationException; import com.fasterxml.jackson.databind.JsonMappingException; import com.fasterxml.jackson.databind.ObjectMapper; import com.sample.model.Employee; public class App { public static void main(String args[]) throws JsonGenerationException, JsonMappingException, IOException { Employee emp = new Employee(); emp.setFirstName("Hari Krishna"); emp.setLastName("Majety"); emp.setId(1); emp.getHobbies().add("Trekking"); emp.getHobbies().add("Blogging"); emp.getHobbies().add("Cooking"); ObjectMapper mapper = new ObjectMapper(); mapper.writeValue(System.out, emp); } }
Output
{"EMPLOYEE_FIRST_NAME":"Hari
Krishna","EMPLOYEE_LAST_NAME":"Majety","EMPLOYEE_DD":1}
No comments:
Post a Comment