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》教程

  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值