Jackson忽略字段不序列化字段的3种方法

首页 / 新闻资讯 / 正文

1、为字段添加@JsonIgnore注解,可以忽略该字段的序列化和反序列化。

@JsonIgnore private String author;

2、使用JsonIgnoreProperties注解忽略多个字段

@JsonIgnoreProperties({ "summary", "author" }) public class ArticleIgnoreProperties {  	private String title; 	private String summary; 	private String content; 	private String author;  }

JsonIgnore作用于单个字段,JsonIgnoreProperties作用于类的多个字段,两者都是用来忽略指定的字段。

除此之外,还有另外一个以JsonIgnore开头的注解JsonIgnoreType,用于忽略指定类型(类、接口)的字段。

JsonIgnoreType注解

使用JsonIgnoreType注解忽略指定类型的字段

在指定的类型上,添加@JsonIgnoreType注解,可以忽略该类型的字段进行序列化。

public class AnimalIgnoreType {  	private String name; 	private Date date; 	private Address address;  	@JsonIgnoreType 	public static class Address { 		private String city; 	} }

使用JsonIgnoreType注解动态忽略指定类型的字段

前面使用JsonIgnoreType注解,忽略的类型是固定的。

利用ObjectMapper的addMixIn方法,可以动态的将JsonIgnoreType注解应用于其他数据类型。

public class AnimalIgnoreType {  	private String name; 	private Date date; 	private Address address;  	public static class Address { 		private String city; 		 	}  }

首先,定义一个空的类,并添加JsonIgnoreType注解。

@JsonIgnoreType public class IgnoreType {}

在序列化时,调用ObjectMapper的addMixIn方法,将JsonIgnoreType注解应用于目标类。

下面的例子,会将IgnoreType类的注解,添加到Date和Address上,因此序列化时这两个类对应的字段会被忽略。

/**  * 调用ObjectMapper的addMixIn方法,将@JsonIgnoreType注解应用于任意目标类.  *   * @throws JsonProcessingException  */ @Test public void mixIn() throws JsonProcessingException { 	AnimalIgnoreType animal = new AnimalIgnoreType(); 	animal.setName("sam"); 	animal.setDate(new Date()); 	 	AnimalIgnoreType.Address address = new AnimalIgnoreType.Address(); 	address.setCity("gz"); 	animal.setAddress(address); 	 	ObjectMapper mapper = new ObjectMapper(); 	mapper.addMixIn(Date.class, IgnoreType.class); 	mapper.addMixIn(Address.class, IgnoreType.class); 	System.out.println(mapper.writeValueAsString(animal)); }

结果:{"name":"sam"}

《轻松学习Jackson》教程