• 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();
    }

  • 相关阅读:
    react.js
    shell if,case,for,while语法
    shell判断文件类型和权限
    shell编程之sed语法
    php魔术方法__SET __GET
    git 忽略文件.gitignore
    php设置错误,错误记录
    linux ifconfig显示 command not found
    数据库备份与恢复
    mysql主要技术
  • 原文地址:https://www.cnblogs.com/maohuidong/p/7992510.html
Copyright © 2020-2023  润新知