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);
}
}
}