Android实现json字符串自动转JavaBean和Map

MrLee2015-6-1624610
简单介绍一下JavaBean。JavaBean是一种JAVA语言写成的可重用组件。为写成JavaBean,类必须是具体的和公共的,并且具有无参数的构造器。JavaBean 通过提供符合一致性设计模式的公共方法将内部域暴露成员属性。众所周知,属性名称符合这种模式,其他Java 类可以通过自身机制发现和操作这些JavaBean 的属性。
在开发http协议的时候我们常常在处理返回的数据,而返回数据是json格式或者是xml,目前json用的较为普遍,因为它体积更小当然速度更快!过程中http接口多,我们每次就要去重复解析各种数据,浪费时间,还不如自己写一个自动生成JavaBean小程序自动生成java类和自动填充数据。 下面是生成java代码的方法:
/**
 * 根据json字符串生成java类
 * @param packName 包名
 * @param className 类名
 * @param jsonString json字符串
 * 如:"data":{
 * "deviceId":"796c57ccac7f4f68a9b0225f951dc739512744664",
 * "deviceSerial":"512744664",
 * "cameraId":"b86d66dc81e046d7a85c8b244d48f017",
 * "cameraNo":1,
 * "cameraName":"DS-2CD3Q10FD-IW(512744664)",
 * "status":0,
 * "isShared":"0",
 * "picUrl":"https://i.ys7.com/assets/imgs/public/companyDevice.jpeg",
 * "isEncrypt":0
 * }
 */
public static void generateJavaFile(String packName, String className,
		String jsonString) {
	try {
		File file = new File(className + ".java");
		if (file.exists())
			file.delete();
		file.createNewFile();
		PrintWriter writer = new PrintWriter(file);
		writer.write("package "+packName+";\n\n");
		writer.write("public class " + className + " {\n\n");
		Map map = JsonHelper.toMap(jsonString);
		Set set = map.keySet();
		String[] keys = new String[set.size()];
		set.toArray(keys);
		for (String key : keys) {
			writer.write("	private String " + key + ";\n");
		}
		writer.write("\n");
		for (String key : keys) {
			String methodKey = key.toUpperCase().charAt(0) + key.substring(1);
			writer.write("	public void set" + methodKey + "(String "+key+") {\n		this."+key+" = "+key+";\n}\n\n");
			writer.write("	public String get"+methodKey+"() {\n		return "+key+";\n	}\n\n");
		}
		writer.write("}");
		writer.flush();
		writer.close();
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	} catch (JSONException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}
}

这里要说明一点,Json字符串只能生成JsonObject,不能是JsonArray。只能是对象!如果是数组必须解析Json数组。。。 下面是完整封装的一个类文件
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Method;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import org.json.JSONException;
import org.json.JSONObject;
/**
 * 1:将JavaBean转换成Map、JSONObject 2:将Map转换成Javabean 3:将JSONObject转换成Map、Javabean
 */
public class JsonHelper {
	/**
	 * 将Javabean转换为Map
	 * @param javaBean javaBean
	 * @return Map对象
	 */
	public static Map toMap(Object javaBean) {
		Map result = new HashMap();
		Method[] methods = javaBean.getClass().getDeclaredMethods();
		for (Method method : methods) {
			try {
				if (method.getName().startsWith("get")) {
					String field = method.getName();
					field = field.substring(field.indexOf("get") + 3);
					field = field.toLowerCase().charAt(0) + field.substring(1);
					Object value = method.invoke(javaBean, (Object[]) null);
					result.put(field, null == value ? "" : value.toString());
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return result;
	}
	/**
	 * 将Json对象转换成Map
	 * @param jsonObject json对象
	 * @return Map对象
	 * @throws JSONException
	 */
	@SuppressWarnings("unchecked")
	public static Map toMap(String jsonString) throws JSONException {
		JSONObject jsonObject = new JSONObject(jsonString);
		Map result = new HashMap();
		Iterator iterator = jsonObject.keys();
		String key = null;
		String value = null;
		while (iterator.hasNext()) {
			key = iterator.next();
			value = jsonObject.getString(key);
			result.put(key, value);
		}
		return result;
	}
	/**
	 * 将JavaBean转换成JSONObject(通过Map中转)
	 * @param bean javaBean
	 * @return json对象
	 */
	public static JSONObject toJSON(Object bean) {
		return new JSONObject(toMap(bean));
	}
	/**
	 * 将Map转换成Javabean
	 * @param javabean javaBean
	 * @param data Map数据
	 */
	public static Object toJavaBean(Object javabean, Map data) {
		Method[] methods = javabean.getClass().getDeclaredMethods();
		for (Method method : methods) {
			try {
				if (method.getName().startsWith("set")) {
					String field = method.getName();
					field = field.substring(field.indexOf("set") + 3);
					field = field.toLowerCase().charAt(0) + field.substring(1);
					method.invoke(javabean, new Object[] { data.get(field) });
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return javabean;
	}
	/**
	 * JSONObject到JavaBean
	 * @param bean javaBean
	 * @return json对象
	 * @throws ParseException json解析异常
	 * @throws JSONException
	 */
	public static void toJavaBean(Object javabean, String jsonString)
			throws ParseException, JSONException {
		JSONObject jsonObject = new JSONObject(jsonString);
		Map map = toMap(jsonObject.toString());
		toJavaBean(javabean, map);
	}
	
	/**
	 * 根据json字符串生成java类
	 * @param packName 包名
	 * @param className 类名
	 * @param jsonString json字符串
	 * 如:"data":{
	 * "deviceId":"796c57ccac7f4f68a9b0225f951dc739512744664",
	 * "deviceSerial":"512744664",
	 * "cameraId":"b86d66dc81e046d7a85c8b244d48f017",
	 * "cameraNo":1,
	 * "cameraName":"DS-2CD3Q10FD-IW(512744664)",
	 * "status":0,
	 * "isShared":"0",
	 * "picUrl":"https://i.ys7.com/assets/imgs/public/companyDevice.jpeg",
	 * "isEncrypt":0
	 * }
	 */
	public static void generateJavaFile(String packName, String className,
			String jsonString) {
		try {
			File file = new File(className + ".java");
			if (file.exists())
				file.delete();
			file.createNewFile();
			PrintWriter writer = new PrintWriter(file);
			writer.write("package "+packName+";\n\n");
			writer.write("public class " + className + " {\n\n");
			Map map = JsonHelper.toMap(jsonString);
			Set set = map.keySet();
			String[] keys = new String[set.size()];
			set.toArray(keys);
			for (String key : keys) {
				writer.write("	private String " + key + ";\n");
			}
			writer.write("\n");
			for (String key : keys) {
				String methodKey = key.toUpperCase().charAt(0) + key.substring(1);
				writer.write("	public void set" + methodKey + "(String "+key+") {\n		this."+key+" = "+key+";\n}\n\n");
				writer.write("	public String get"+methodKey+"() {\n		return "+key+";\n	}\n\n");
			}
			writer.write("}");
			writer.flush();
			writer.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (JSONException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
}


本文链接:http://www.ithtw.com/thread-3472.htm
转载请注明:2015-6-16 于 IT十万个为什么 发表
推荐阅读
最新回复 (0)
回复
登录发表 or 还没有账号?去注册