如何在 Java 中使用 Jackson 进行序列化时忽略某个类?
javajsonobject oriented programmingprogramming更新于 2025/7/17 13:00:17
Jackson @JsonIgnoreType 注释可用于在序列化过程中忽略某个类,并且它可以标记在序列化和反序列化 JSON 对象时要忽略的类的所有属性或字段。
语法
@Target(value={ANNOTATION_TYPE,TYPE})
@Retention(value=RUNTIME)
public @interface JsonIgnoreType
示例
import com.fasterxml.jackson.annotation.*;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.*;
import java.io.*;
public class JsonIgnoreTypeTest {
public static void main(String args[]) throws IOException {
Employee emp = new Employee();
ObjectMapper mapper = new ObjectMapper();
String jsonString = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(emp);
System.out.println(jsonString);
}
}
// Employee class
class Employee {
@JsonIgnoreType public static class Address {
public String firstLine = null;
public String secondLine= null;
public String thirdLine = null;
@Override
public String toString() {
return "Address{" +
"firstLine='" + firstLine+ '\'' +
", secondLine='" + secondLine+ '\'' +
", thirdLine='" + thirdLine + '\'' +
'}';
}
} // end of Address class
public long empId = 115;
public String empName = "Raja Ramesh";
public Address empAddress = new Address();
@Override
public String toString() {
return "Employee{" +
"empId=" + empId +
", empName='" + empName + '\'' +
", empAddress=" + empAddress +
'}';
}
}
输出
{
"empId" : 115,
"empName" : "Raja Ramesh"
}
相关文章
有用资源
java 参考教程 - 该教程包含有关 java 的更多信息:https://www.cainiaomax.com/java/

