/*
* 第一種:在對象響應字段前加注解
* @JSONField(serialize=false)
* private String name;
*/
/*
* 第二種:在對象對應字段前面加transient,表示該字段不用序列化
* private transient String name;
*/
/*
* 第三種
* PropertyFilter profilter = new PropertyFilter(){
@Override
public boolean apply(Object object, String name, Object value) {
if(name.equalsIgnoreCase("last")){
//false表示last字段將被排除在外
return false;
}
return true;
}
};
json = JSON.toJSONString(user, profilter);
System.out.println(json);
*/
/*
* 第四種,直接填寫屬性
* SimplePropertyPreFilter filter = new SimplePropertyPreFilter(TTown.class, "id","townname");
response.getWriter().write(JSONObject.toJSONString(townList,filter));
*/
//第五種:深層次過濾 (限高版本)
//TTown1對象中有屬性名稱為TTown2對象,只需要TTown1的id屬性包括TTown2對象的id屬性
SimplePropertyPreFilter filter1 = new SimplePropertyPreFilter(TTown1.class, "id","townname");
SimplePropertyPreFilter filter2 = new SimplePropertyPreFilter(TTown2.class, "id","townname");
SerializeFilter[] filters=new SerializeFilter[]{filter1,filter2};
System.out.println(JSONObject.toJSONString(result, filters));
//第六種:深層次過濾,實現PropertyPreFilter
public class ComplexPropertyPreFilter implements PropertyPreFilter {
private Map<Class<?>, String[]> includes = new HashMap<Class<?>, String[]>();
private Map<Class<?>, String[]> excludes = new HashMap<Class<?>, String[]>();
static {
JSON.DEFAULT_GENERATE_FEATURE |= SerializerFeature.DisableCircularReferenceDetect.getMask();
}
public ComplexPropertyPreFilter() {
}
public ComplexPropertyPreFilter(Map<Class<?>, String[]> includes) {
super();
this.includes = includes;
}
@Override
public boolean apply(JSONSerializer serializer, Object source, String name) {
//對象為空。直接放行
if (source == null) {
return true;
}
// 獲取當前需要序列化的對象的類對象
Class<?> clazz = source.getClass();
// 無需序列的對象、尋找需要過濾的對象,可以提高查找層級
// 找到不需要的序列化的類型
for (Map.Entry<Class<?>, String[]> item : this.excludes.entrySet()) {
// isAssignableFrom(),用來判斷類型間是否有繼承關系
if (item.getKey().isAssignableFrom(clazz)) {
String[] strs = item.getValue();
// 該類型下 此 name 值無需序列化
if (isHave(strs, name)) {
return false;
}
}
}
// 需要序列的對象集合為空 表示 全部需要序列化
if (this.includes.isEmpty()) {
return true;
}
// 需要序列的對象
// 找到不需要的序列化的類型
for (Map.Entry<Class<?>, String[]> item : this.includes.entrySet()) {
// isAssignableFrom(),用來判斷類型間是否有繼承關系
if (item.getKey().isAssignableFrom(clazz)) {
String[] strs = item.getValue();
// 該類型下 此 name 值無需序列化
if (isHave(strs, name)) {
return true;
}
}
}
return false;
}
/*
* 此方法有兩個參數,第一個是要查找的字符串數組,第二個是要查找的字符或字符串
*/
public static boolean isHave(String[] strs, String s) {
for (String str : strs) {
// 循環查找字符串數組中的每個字符串中是否包含所有查找的內容
if (str.equals(s)) {
// 查找到了就返回真,不在繼續查詢
return true;
}
}
// 沒找到返回false
return false;
}
public Map<Class<?>, String[]> getIncludes() {
return includes;
}
public void setIncludes(Map<Class<?>, String[]> includes) {
this.includes = includes;
}
public Map<Class<?>, String[]> getExcludes() {
return excludes;
}
public void setExcludes(Map<Class<?>, String[]> excludes) {
this.excludes = excludes;
}
}