日期:2014-05-16  浏览次数:20397 次

java对象与json字符串互转的工具类

import java.beans.PropertyDescriptor;

import java.lang.reflect.Array;
import java.lang.reflect.InvocationTargetException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import ognl.OgnlOps;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.json.JSONArray;
import org.json.JSONObject;

import com.opensymphony.xwork.util.OgnlUtil;


/**
 * java对象与json字符串互转的工具类
 * 
 */

public class JsonUtil {

	
	/**
	 * 将json字符串转成javabean
	 * @param jsonStr 要转换的json字符串
	 * @param toClass 要转化到的类型
	 * @param childMap 该类型中集合字段的字段名和集合元素类型map
	 * @return Object 
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 * @throws IllegalArgumentException 
	 */
	@SuppressWarnings("unchecked")
    public static Object json2Bean(Class toClass,String  jsonValue,Map<String,Class> childMap) throws Exception{
		if( toClass == null || StringUtils.isBlank(jsonValue)) {
			return null;
		}
		    try{
		     jsonValue	= URLDecoder.decode(jsonValue, "utf-8");
		    }catch(Exception e){
		    	throw new Exception("编码格式错误!");
		    }
			JSONObject object = null;
			try{
				 object= new JSONObject(jsonValue);
			}catch(Exception e){
				throw new Exception("json格式错误!");
			}	
			Object obj = toClass.newInstance();
			
			Map<String,Object> sourceMap = toMap(object);
			PropertyDescriptor[] props = OgnlUtil.getPropertyDescriptors(obj);
			Map<String,Object> map = new HashMap<String,Object>();
			//参数不区分大小写
			for (PropertyDescriptor desc : props) {
			  Set entrys =  sourceMap.entrySet();
			  boolean contains = false;
			  for(Iterator i = entrys.iterator();i.hasNext();){
				  Entry entry = (Entry) i.next();
				  if(((String)entry.getKey()).equalsIgnoreCase(desc.getName())){
					  map.put(desc.getName(), entry.getValue());
					  contains = true;
				       break;
				  }
			  }
			  
				if( contains ) {
					Object value = null;
					// 处理日期型
					// "yyyy-MM-dd'T'HH:mm:ss'Z'"此格式是由json2.js转换后的Date格式
					if(java.util.Date.class.isAssignableFrom(desc.getPropertyType())) {
						  String date = (String) map.get(desc.getName());
						  if(!validateDate(date)){
							  throw new Exception(desc.getName()+"日期格式错误!");
						  }						 
						  value = new SimpleDateFormat("yyyy-MM-dd").parse(date.trim());
					} else if(java.sql.Date.class.isAssignableFrom(desc.getPropertyType())) {
							String date = (String) map.get(desc.getName());
							 if(!validateDate(date)){
								  throw new Exception(desc.getName()+"日期格式错误!");
							  }	
							  value  = new java.sql.Date(new SimpleDateFormat("yyyy-MM-dd").parse(
										date.trim()).getTime());
					}
					  else if(Collection.class.isAssignableFrom(desc.getPropertyType()))
					  {
						  Class clz =  childMap.get(desc.getName());
						  if(clz.isPrimitive() || CharSequence.class.isAssignableFrom(clz) || Number.class.isAssignableFrom(clz))
							   value = convertFromStringListSimple(map.get(desc.getName()).toString(),clz);
						  else value = convertFromStringListComplex(map.get(desc.getName()).toString(),clz);
					  }
					  else {
						  
						  if(desc.getPropertyType().isPrimitive() || CharSequence.class.isAssignableFrom(desc.getPropertyType())
								  || Number.class.isAssignableFrom(desc.getPropertyType())){
							  try{
						 value = OgnlOps.convertValue(map.get(desc.getName()),
								desc.getPropertyType());
							  }catch(NumberFormatException e){
								  Class clz = desc.getPropertyType();
									if(clz == Integer.TYPE||clz == Short.TYPE||clz == Long.TYPE||clz == BigInteger.c