自己写的一个Java Bean转换为HashMap及ArrayList容器的功能类,支持Hibernate

XStream转换Object生成类结构垃圾数据太多了,影响网络,仿照之前的JSON工具类的写法,自己又写了个转换到仅HashMap和ArrayList容器的类来做一下处理。

思路主要就是把Bean的成员转换到HashMap,而Colecction和数组类型转换到ArrayList。这下除了原始类型外,就只包含HashMap和ArrayList两个JAVA类了。

这样做转换处理后,再用XStream做一下转换成的数据。。。哇,这下世界清洁多了:)

package  com.aherp.framework.util;

import  java.lang.reflect.Array;
import  java.lang.reflect.Method;
import  java.util.ArrayList;
import  java.util.Collection;
import  java.util.HashMap;
import  java.util.Iterator;
import  java.util.Map;

import  org.json.JSONException;

/**
 * 转换工具类,支持反射的方式将对象转换为Map,将数组和Collection转换为List供XStrem使用
 * 
@author Jim Wu
 *
 
*/

public   class  ObjMapListUtil  {

    
private static ObjMapListUtil instance = null;

    
static public Object toHashMap(Object obj) throws JSONException{
        
return toHashMap(obj, false);
    }

    
    
static public Object toHashMap(Object obj, boolean useClassConvert) throws JSONException{
        
if(instance == null)
            instance 
= new ObjMapListUtil();
        
return instance.getMapListObject(obj, useClassConvert);
    }


    
/**
     * 代理类是否输出的检查,返回true则允许继续转换
     * 
@param bean
     * 
@return
     
*/

    
protected boolean canProxyOutput(Object bean) {
        
return true;
    }


    
/**
     * 代理类时做的检查.返回应该检查的对象.
     * 
@param bean
     * 
@return
     
*/

    
protected Object proxyConvert(Object bean){
        
return bean;
    }


    
public Object getMapListObject(Object bean, boolean useClassConvert){

        
if(bean == null)
            
return null;
        bean 
= proxyConvert(bean);
        Class clazz 
= bean.getClass();
        
if(bean instanceof Number || bean instanceof Boolean || bean instanceof String){
            
return bean;
        }

        
if(clazz.isArray()){

            ArrayList
<Object> arrayList = new ArrayList<Object>();

            
int arrayLength = Array.getLength(bean);
            
for(int i = 0; i < arrayLength; i ++){
                Object rowObj 
= Array.get(bean, i);
                
if(canProxyOutput(rowObj))
                    arrayList.add(getMapListObject(rowObj, useClassConvert));
            }

            
return arrayList;
        }

        
if(bean instanceof Collection){
            
            ArrayList
<Object> arrayList = new ArrayList<Object>();
            
            Iterator iterator 
= ((Collection)bean).iterator();
            
while(iterator.hasNext()){
                Object rowObj 
= iterator.next();
                
if(canProxyOutput(rowObj))
                    arrayList.add(getMapListObject(rowObj, useClassConvert));
            }

            
return arrayList;
        }

        
if(bean instanceof Map){
            HashMap
<String, Object> beanMap = new HashMap<String, Object>();

            Map map 
= (Map)bean;
            Iterator iterator 
= map.keySet().iterator();
            
while(iterator.hasNext()){
                Object key 
= iterator.next();
                Object rowObj 
= map.get(key);
                
if(canProxyOutput(rowObj))
                    beanMap.put(key.toString(), getMapListObject(rowObj, useClassConvert));
            }

            
return beanMap;
        }


        HashMap
<String, Object> beanMap = new HashMap<String, Object>();
        Class klass 
= bean.getClass();
        Method[] methods 
= klass.getMethods();
        
for (int i = 0; i < methods.length; i ++{
            
try {
                Method method 
= methods[i];
                String name 
= method.getName();
                String key 
= "";
                
if (name.startsWith("get")) {
                    key 
= name.substring(3);
                }
 else if (name.startsWith("is")) {
                    key 
= name.substring(2);
                }

                
if (key.length() > 0 &&
                        Character.isUpperCase(key.charAt(
0)) &&
                        method.getParameterTypes().length 
== 0{
                    
if (key.length() == 1{
                        key 
= key.toLowerCase();
                    }
 else if (!Character.isUpperCase(key.charAt(1))) {
                        key 
= key.substring(01).toLowerCase() +
                            key.substring(
1);
                    }

                    Object elementObj 
= method.invoke(bean);
                    
if(elementObj instanceof Class){
                        
if(useClassConvert)
                            beanMap.put(key, elementObj.toString());
                    }

                    
else{
                        
if(canProxyOutput(elementObj))
                            beanMap.put(key, getMapListObject(elementObj, useClassConvert));
                    }

                }

            }
 catch (Exception e) {
                
/* forget about it */
            }

        }

        
return beanMap;
    }


    
}


支持Hibernate的类则继承一下,覆盖proxyConvert和canProxyOutput方法
package  com.aherp.framework.util;

import  org.hibernate.collection.PersistentSet;
import  org.hibernate.proxy.HibernateProxy;
import  org.hibernate.proxy.LazyInitializer;
import  org.json.JSONException;

/**
 * 扩展为支持Hibernate的工具方法.
 * 
@author Jim Wu
 *
 
*/

public   class  HiObjMapListUtil  extends  ObjMapListUtil  {

    
private static HiObjMapListUtil instance = null;

    
static public Object toHashMap(Object obj) throws JSONException{
        
return toHashMap(obj, false);
    }

    
    
static public Object toHashMap(Object obj, boolean useClassConvert) throws JSONException{
        
if(instance == null)
            instance 
= new HiObjMapListUtil();
        
return instance.getMapListObject(obj, useClassConvert);
    }


    @Override
    
protected Object proxyConvert(Object bean) {
        
if(bean instanceof HibernateProxy){
            LazyInitializer lazyInitializer 
= ((HibernateProxy)bean).getHibernateLazyInitializer();
            
if(lazyInitializer.isUninitialized()){
                
return lazyInitializer.getIdentifier();
            }
else
                
return lazyInitializer.getImplementation();
        }

        
if(bean instanceof PersistentSet){
            
return new String[]{}//忽略hibernate one-to-many
        }

        
return bean;
    }


    @Override
    
protected boolean canProxyOutput(Object bean) {
            
return !(bean != null && bean instanceof PersistentSet);
    }

}


P.S.发现Hibernate Session的get方法拿到的对象仅填充了一个OID而已,需要Hibernate.initialize才能继续拿到整个实体的数据。这样XStream转换才正确,否则就是一个仅OID的List而已了
  • 0
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值