如果 Java 对象中有不希望被序列化的字段,我们可以使用 Jackson 库中的@JsonIgnore 注解。可以在字段级别使用@JsonIgnore,用于在序列化和反序列化期间忽略字段。
语法public @interface JsonIgnore
示例import .*;
import .*;
import .*;
import .*;
import .*;
public class JsonIgnoreAnnotationTest {
public static void main(String args[]) throws JsonGenerationException, JsonMappingException, IOException {
Employee emp = new Employee();
("Raja");
("Ramesh");
(120);
().add("Java");
().add("Scala");
().add("Python");
ObjectMapper mapper = new ObjectMapper();
().writeValue(, emp);
}
}
//员工阶层
@JsonInclude(.NON_NULL)
@JsonPropertyOrder({
"firstName",
"lastName",
"technologies",
"empId"
})
class Employee { @JsonProperty("EMPLOYEE_ID")
private int empId;
@JsonProperty("EMPLOYEE_FIRST_NAME")
private String firstName;
@JsonProperty("EMPLOYEE_LAST_NAME")
private String lastName;
@JsonIgnore private List technologies = new ArrayList<>();
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
= empId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
= firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
= lastName;
}
public List getTechnologies() {
return technologies;
}
public void setTechnologies(List technologies) {
= technologies;
}
}
输出结果{
"EMPLOYEE_FIRST_NAME" : "Raja",
"EMPLOYEE_LAST_NAME" : "Ramesh",
"EMPLOYEE_ID" : 120
}