zoukankan      html  css  js  c++  java
  • Jsonlib 属性过滤器

    /**
    * @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();
    }

  • 相关阅读:
    jQuery实现横向滚动切换选中
    jQuery源码分析(6)
    jQuery源码分析(5)
    jQuery源码分析(4)
    jQuery源码分析(3)
    jQuery源码分析(2)
    jQuery源码分析(1)
    gulp搭建前端自动化开发环境
    iview表格动态数据实现合并功能
    iview动态表格实现并实现单行可增删(表头与内容都是动态获取)----完整版
  • 原文地址:https://www.cnblogs.com/maohuidong/p/7992510.html
Copyright © 2011-2022 走看看