过滤懒加载代理对象(该端代码原文地址找不到了)
package com.pbh.filter;
import org.hibernate.collection.spi.PersistentCollection;
import org.hibernate.proxy.HibernateProxy;
import org.hibernate.proxy.LazyInitializer;
import com.alibaba.fastjson.serializer.PropertyFilter;
/** * * Description: 过滤Hibernate懒加载不能序列化对象 * @author PanBaihui * @time 2017年9月15日 下午4:15:45 */
public class SimplePropertyFilter implements PropertyFilter {
@Override
public boolean apply(Object object,String name,Object value) {
if (value instanceof HibernateProxy) {//hibernate代理对象
LazyInitializer initializer = ((HibernateProxy) value).getHibernateLazyInitializer();
if (initializer.isUninitialized()) {
return false;
}
} else if (value instanceof PersistentCollection) {//实体关联集合一对多等
PersistentCollection collection = (PersistentCollection) value;
if (!collection.wasInitialized()) {
return false;
}
Object val = collection.getValue();
if (val == null) {
return false;
}
}
return true;
}
}
通用实现
public class ComplexPropertyPreFilter implements PropertyFilter {
private Map<Class<?>,Set<String>> includeMap = new HashMap<Class<?>,Set<String>>();
//@Override
public boolean apply(Object source,Object value) {
for(Entry<Class<?>,Set<String>> entry : includeMap.entrySet()) {
Class<?> class1 = entry.getKey();
if(source.getClass() == class1){
Set<String> fields = entry.getValue();
for(String field : fields) {
if(field.equals(name)){
return false;
}
}
}
}
return true;
}
public ComplexPropertyPreFilter(Map<Class<?>,Set<String>> includeMap){
this.includeMap = includeMap;
}
}
原文链接:https://www.f2er.com/json/288753.html