java应用在进行系统间通信时,经常会使用json格式进行数据传输交换。利用alibaba fastjson(本文使用的是1.2.46),对象与json字符串的相互转换非常的便利。
但是,在对对象进行json序列化时,经常会出现以下的场景:对象的类是一个与数据库表相关的业务实体类,如以下实体类:
public class DiagramEntity {
private String name;
private String code;
private int beginDate;
private int endDate;
private int flag;
private String createId;
private int createDate;
// 访问器定义
}
其对应的数据库表字段如下:
字段名 | 类型 |
name | varchar(36) |
code | varchar(36) |
beginDate | Integer |
endDate | Integer |
flag | Integer |
createId | varchar(36) |
createDate | Integer |
然而,在向客户端或者对手系统传输数据时,我们可能会在运行时选择性的进行某些属性的传输,比如对以上的类,仅需要传输name、code、beginDate、endDate,其余的属性不需要传输。遇到此种情况我们可以使用fastjson提供的com.alibaba.fastjson.serializer.SimplePropertyPreFilter类,创建一个此类的对象,然后利用其getExcludes()方法,添加不需要进行序列化的属性。
为了更加的方便使用过滤属性,本文对SimplePropertyPreFilter类进行了微小扩展,实现了SimplePropertyPreFilterEx类,在后者中增加了一个带三个参数的构造函数:
public SimplePropertyPreFilterEx(Class<?> clazz, String[] includeProperties, String[] excludeProperties);
以更方便的设置序列化时包含或者排除的属性。如以下使用:
@Test
public void testJsonExcludes() {
SimplePropertyPreFilterEx objFilter = new SimplePropertyPreFilterEx(null, null,
new String[] {"flag", "createId", "createDate"});
DiagramEntity objMessage = new DiagramEntity();
objMessage.setName("张三三");
objMessage.setCode("X001");
String strRet = JSON.toJSONString(objMessage, objFilter);
System.out.println(strRet);
}
输出结果:
{"beginDate":0,"code":"X001","endDate":0,"name":"张三三"}
附:SimplePropertyPreFilterEx类定义示例:
package com.bn.zbase.message.util;
/**
* Copyright 1999-2017 Alibaba Group.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import com.alibaba.fastjson.serializer.SimplePropertyPreFilter;
import java.util.Collections;
public class SimplePropertyPreFilterEx extends SimplePropertyPreFilter {
public SimplePropertyPreFilterEx(String... includeProperties){
super(null, includeProperties);
}
public SimplePropertyPreFilterEx(Class<?> clazz, String... includeProperties){
super(clazz, includeProperties);
}
public SimplePropertyPreFilterEx(Class<?> clazz, String[] includeProperties, String[] excludeProperties) {
super(clazz, includeProperties == null ? new String[0] : includeProperties);
if (excludeProperties != null && excludeProperties.length > 0) {
Collections.addAll(getExcludes(), excludeProperties);
}
}
}