/**
* @title JSON转换属性过滤器
* @description 用于JSON lib的JSON转换
* @author maohuidong
* @date 2017-04-06
*/
public class JsonConvertPropertyFilter implements PropertyFilter {
/**
* @function apply
* @param obj:待转换的对象 s: 对象的属性 value:对象的属性值
* @description JSON转换属性过滤器(Hibernate)
* @return true:过滤 false:不过滤
* @author maohuidong
* @date 2017-04-06
*/
@Override
public boolean apply(Object obj, String s, Object value) {
// hibernate代理对象未初始化,则过滤掉
if (value instanceof HibernateProxy) {
LazyInitializer initializer = ((HibernateProxy) value)
.getHibernateLazyInitializer();
if (initializer.isUninitialized()) {
return true;
}
}
// Hibernate持久化集合为初始化,则过滤掉(实体关联一对多)
if (value instanceof PersistentCollection) {
PersistentCollection collection = (PersistentCollection) value;
if (!collection.wasInitialized()) {
return true;
}
}
return false;
}
}

 

 

 

/**
* @function objStreamOutput
* @param 无
* @description 输出流封装
* @return 无
* @author maohuidong
* @date 2017-04-09
*/
protected void objStreamOutput(Object object,List<String> fieldFilter) throws IOException{
HttpServletResponse response = ServletActionContext.getResponse();
response.setCharacterEncoding("utf-8");
PrintWriter pWriter = response.getWriter();
//Json过滤
JsonConfig jsonConfig = new JsonConfig();
jsonConfig.setIgnoreDefaultExcludes(false);
if(fieldFilter == null){
fieldFilter = new ArrayList<String>();
}
//Json转换过滤没用的字段
fieldFilter.add("hibernateLazyInitializer");
String[] filter = new String[fieldFilter.size()];
filter = fieldFilter.toArray(filter);
jsonConfig.setExcludes(filter);
//Json转换过滤未初始化的数据
jsonConfig.setJsonPropertyFilter(new JsonConvertPropertyFilter());
//结果转换为json字符串
String str = "";
//结果集能实例化为List
if(object instanceof List){
JSONArray jsonArray = JSONArray.fromObject(object, jsonConfig);
str = jsonArray.toString();
}else if(object instanceof String){
str = (String) object;
}else if(object instanceof Number){
str = object.toString();
}
else{
JSONObject jsonObject = JSONObject.fromObject(object, jsonConfig);
str = jsonObject.toString();
}
pWriter.print(str);
pWriter.flush();
pWriter.close();
}

posted on 2017-12-06 14:28  毛会懂  阅读(155)  评论(0编辑  收藏  举报