json网络数据传输--HttpJsonAdapter

服务器端与客户端之前通过json数据传输,客户端跟服务器端之前的javabean与String之间的转换

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.List;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;

public class HttpJsonAdapter {

	private static HttpJsonAdapter instance = null;

	private HttpJsonAdapter() {
	}

	public static synchronized HttpJsonAdapter getInstance() {
		if (instance == null) {
			instance = new HttpJsonAdapter();
		}
		return instance;
	}

	// json转为带泛型的list
	public <T> List<T> gets(String str, Class<T> clazz) {
	        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")
	                 .create();
	         // json转为带泛型的list
	         return gson.fromJson(str, new TypeToken<List<T>>() {
	         }.getType());
	    }

	public <T> T get(String str, Class<T> clazz) throws BizException {
		Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss")
				.create();
		try {
			return (T) gson.fromJson(str, clazz);
		} catch (Exception e) {
			throw new BizException("数据处理异常", e);
		}
	}

	public static String getMapToJson(Object obj) {
		Gson gson = new Gson();
		HashMap<String, Object> objmap = new HashMap<String, Object>();
		return gson.toJson(toGson(objmap, obj, obj.getClass()));
	}

	/** 只支持继承 * */
	@SuppressWarnings("unchecked")
	public static HashMap<String, Object> toGson(
			HashMap<String, Object> objmap, Object obj, Class clazz) {
		// 父类
		Class SuperClass = clazz.getSuperclass();
		// 接口数组
		// Class[] InterClass=clazz.getInterfaces();
		Field[] ffields = clazz.getSuperclass().getDeclaredFields();
		Field[] fields = clazz.getDeclaredFields();
		for (Field field : fields) {
			boolean flag = field.isAccessible();
			field.setAccessible(true);
			try {
				objmap.put(field.getName(), field.get(obj));
			} catch (IllegalArgumentException e) {
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
			field.setAccessible(flag);
		}
		for (Field field : ffields) {
			boolean flag = field.isAccessible();
			field.setAccessible(true);
			try {
				objmap.put(field.getName(), field.get(obj));
			} catch (IllegalArgumentException e) {

			} catch (IllegalAccessException e) {
				e.printStackTrace();
			}
			field.setAccessible(flag);
		}
		if (SuperClass != Object.class) {
			return toGson(objmap, obj, SuperClass);
		} else {
			return objmap;
		}
	}

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值