Fastjson通过SimplePropertyPreFilter过滤属性

package com.avic.common.utils;

import java.util.Date;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;

public class Demo {
	
	public static void main(String[] args) {
	    User user=new User();
	    user.setId(1);
	    user.setUserName("admin");
	    user.setPassword("123456");
	    user.setSex("男");
	    user.setBirthday(new Date());
	    String userJSON=JSON.toJSONString(user);
		String userJSON2=JSON.toJSONString(user,new SimplePropertyPreFilter(User.class, "userName","sex"));
		SimplePropertyPreFilter simplePropertyPreFilter = new SimplePropertyPreFilter(User.class, "userName","sex");
		simplePropertyPreFilter.getExcludes().add("sex");//添加排除属性
		simplePropertyPreFilter.getIncludes().add("birthday");//添加属性
		String userJSON3=JSON.toJSONString(user,simplePropertyPreFilter);
		System.out.println("userJSON"+userJSON);
		System.out.println("userJSON2使用了SimplePropertyPreFilter过滤器--->"+userJSON2);
		System.out.println("userJSON3使用了SimplePropertyPreFilter过滤器添加或排除属性--->"+userJSON3);
	}
	
	static class User{
	    private int id;
	    private String userName;
	    private String password;
	    private String sex;
	    private String age;
	    private Date birthday;
	    
		public int getId() {
			return id;
		}
		public void setId(int id) {
			this.id = id;
		}
		public String getUserName() {
			return userName;
		}
		public void setUserName(String userName) {
			this.userName = userName;
		}
		public String getPassword() {
			return password;
		}
		public void setPassword(String password) {
			this.password = password;
		}
		public String getSex() {
			return sex;
		}
		public void setSex(String sex) {
			this.sex = sex;
		}
		public String getAge() {
			return age;
		}
		public void setAge(String age) {
			this.age = age;
		}
		public Date getBirthday() {
			return birthday;
		}
		public void setBirthday(Date birthday) {
			this.birthday = birthday;
		}
	}
}

运行结果:

userJSON{"birthday":1563524469169,"id":1,"password":"123456","sex":"男","userName":"admin"}
userJSON2使用了SimplePropertyPreFilter过滤器--->{"sex":"男","userName":"admin"}
userJSON3使用了SimplePropertyPreFilter过滤器添加或排除属性--->{"birthday":1563524469169,"userName":"admin"}

com.alibaba.fastjson版本

<dependency> 
  <groupId>com.alibaba</groupId>  
  <artifactId>fastjson</artifactId>  
  <version>1.2.35</version> 
</dependency>

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值