/*
* 第一种:在对象响应字段前加注解
* @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;
}
}