如何在 Java 中忽略 JSON 序列化过程中的字段?
如果 Java 对象中存在不想序列化的字段,可以在 Jackson 库中使用 @JsonIgnore 注解。@JsonIgnore 可用于字段级别,在 **序列化** 和 **反序列化** 过程中忽略字段。
语法
public @interface JsonIgnore
示例
import java.io.*;
import java.util.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.annotation.*;
public class JsonIgnoreAnnotationTest {
public static void main(String args[]) throws JsonGenerationException, JsonMappingException, IOException {
Employee emp = new Employee();
emp.setFirstName("Raja");
emp.setLastName("Ramesh");
emp.setEmpId(120);
emp.getTechnologies().add("Java");
emp.getTechnologies().add("Scala");
emp.getTechnologies().add("Python");
ObjectMapper mapper = new ObjectMapper();
mapper.writerWithDefaultPrettyPrinter().writeValue(System.out, emp);
}
}
// Employee class
@JsonInclude(JsonInclude.Include.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<String> technologies = new ArrayList<>();
public int getEmpId() {
return empId;
}
public void setEmpId(int empId) {
this.empId = empId;
}
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> getTechnologies() {
return technologies;
}
public void setTechnologies(List<String> technologies) {
this.technologies = technologies;
}
}输出
{
"EMPLOYEE_FIRST_NAME" : "Raja",
"EMPLOYEE_LAST_NAME" : "Ramesh",
"EMPLOYEE_ID" : 120
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP