Json转换为Java对象

package com.chinatech.common.utils;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;


import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;




/**
 * the tool class for change json to object
 * @author wanggang
 * Email: [email protected]
 *
 */
public class Json2Bean {

	private static final boolean DEBUG = true;


	@SuppressWarnings("unchecked")
	public static <T> T getBean(String content, Class<T> beanClass)   {
		if(DEBUG)Logger.i(content);
		T bean = null;
		try {
			JSONObject jsonObject = new JSONObject(content);
			Iterator<String> keys = jsonObject.keys();
			bean = beanClass.newInstance();
			while(keys.hasNext()) {
				String key = keys.next();
				if(DEBUG)Logger.i("the field is '"+key+"'");
				Field field;
				try {
					field = beanClass.getDeclaredField(key);
					field.setAccessible(true);  
					field.set(bean, jsonObject.get(key));
				} catch (NoSuchFieldException e) {
					Logger.e("NoSuchFieldException");
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (IllegalAccessException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}
		} catch (InstantiationException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (IllegalAccessException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return bean;
	}

	@SuppressWarnings("rawtypes")
	public static <T> List getList(String content, Class<T> beanClass) {
		List<T> list;
		if(DEBUG)Logger.i(content);
		JSONArray jsonArray=null;
		try {
			jsonArray = new JSONArray(content);
		} catch (JSONException e) {
			Logger.e("The wrong JSON data format");
			return null;
		}
		list=new ArrayList<T>();
		for(int i=0;i<jsonArray.length();i++){
			JSONObject jsonObject = (JSONObject)jsonArray.opt(i);
			if(jsonObject!=null){

				list.add(getBean(jsonObject.toString(),beanClass));
			}
		}
		return list;
	}
	@SuppressWarnings("rawtypes")
	public static <T> LinkedList getLinkedList(String content, Class<T> beanClass) {
		LinkedList<T> list;
		if(DEBUG)Logger.i(content);
		JSONArray jsonArray=null;
		try {
			jsonArray = new JSONArray(content);
		} catch (JSONException e) {
			Logger.e("The wrong JSON data format");
			return null;
		}
		list=new LinkedList<T>();
		for(int i=0;i<jsonArray.length();i++){
			JSONObject jsonObject = (JSONObject)jsonArray.opt(i);
			if(jsonObject!=null){

				list.add(getBean(jsonObject.toString(),beanClass));
			}
		}
		return list;
	}
}
 

猜你喜欢

转载自09572.iteye.com/blog/1715690