问题描述
现在遇到了一个麻烦我有一个复杂对象json串,比如:{"status":1,"data":{"uid":"1111","data":{"name":"aname","age":11}}}(实际上比这个还要复杂很多)这个时候,我通过自己写的代码解析这个json串生成了对应结构的java物理文件,下面是我的代码(很乱,也没注释……其实和问题本身无关,可以不看)JSONBeanUtil package browser.json.util;import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Set;import net.sf.json.JSONArray;import net.sf.json.JSONObject;import browser.json.impl.BeanImpl;import browser.json.impl.PropertyImpl;import browser.json.itf.IProperty;public class JSONBeanUtil {private String jsonString;private String className;private String classPackage;public JSONBeanUtil(String jsonString, String className, String classPackage) {this.jsonString = jsonString;this.className = className;this.classPackage = classPackage;}@SuppressWarnings("rawtypes")public HashMap<String, Class> getJsonMap() throws ClassNotFoundException {return this.putJsonMap(new HashMap<String, Class>(), this.jsonString,this.className, this.classPackage);}public void writeJsonBean() {this.writeJsonBean(this.jsonString, this.className, this.classPackage);}private void writeJsonBean(String strJson, String parentKey,String packageStr) {JSONObject jo = JSONObject.fromObject(strJson);@SuppressWarnings("unchecked")Set<Object> keySet = jo.keySet();Object[] array = keySet.toArray();BeanImpl bean = new BeanImpl();List<IProperty> popatryList = new ArrayList<IProperty>();List<String> importList = new ArrayList<String>();IProperty popatry = (IProperty) new PropertyImpl();for (Object key : array) {String fieldName = key.toString();popatry = (IProperty) new PropertyImpl();String value = jo.getString(fieldName);String firestUp = FreeMarkerUtil.firestUp(fieldName);switch (getFlag(value)) {case 1:popatry.setFiledType("String");break;case 2:popatry.setFiledType(firestUp);importList.add(packageStr + "." + fieldName + "." + firestUp);writeJsonBean(value, fieldName, packageStr + "." + fieldName);break;case 3:String firestJsonArray = getFirestJsonArray(value);if (firestJsonArray.equals("DO1")) {popatry.setFiledType("List<String>");} else {writeJsonBean(firestJsonArray, fieldName, packageStr + "."+ fieldName);popatry.setFiledType("List<" + firestUp + ">");importList.add(packageStr + "." + fieldName + "."+ firestUp);}importList.add("java.util.List");break;}popatry.setFiledName(FreeMarkerUtil.firestLow(fieldName));popatry.setIoFunction(firestUp);popatryList.add(popatry);}bean.setImportList(importList);bean.setClassName(FreeMarkerUtil.firestUp(parentKey));bean.setPackageName(packageStr);bean.setPopatryList(popatryList);FreeMarkerUtil.writeJavaBean(bean);}@SuppressWarnings("rawtypes")private Class getClass(String path) throws ClassNotFoundException {Class cl = Class.forName(path);return cl;}private String getFirestJsonArray(String value) {if (value.length() > 2) {JSONArray ja = JSONArray.fromObject(value);Object[] array = ja.toArray();String string = array[0].toString();if (string.length() > 2) {String flag = string.substring(0, 1)+ string.substring(string.length() - 1, string.length());if (flag.equals("{}")) {return string;} else {return "DO1";}} else {return "DO1";}} else {return "DO1";}}private int getFlag(String value) {if (value.length() > 1) {String flag = value.substring(0, 1)+ value.substring(value.length() - 1, value.length());if (flag.equals("[]")) {return 3;}if (flag.equals("{}")) {return 2;} else {return 1;}} else {return 1;}}public String getJsonString() {return jsonString;}public void setJsonString(String jsonString) {this.jsonString = jsonString;}public String getClassName() {return className;}public void setClassName(String className) {this.className = className;}public String getClassPackage() {return classPackage;}public void setClassPackage(String classPackage) {this.classPackage = classPackage;}}FreeMarkerUtil package browser.json.util;import java.io.File;import java.io.FileOutputStream;import java.io.IOException;import java.io.OutputStreamWriter;import java.io.Writer;import java.util.HashMap;import java.util.Map;import java.util.StringTokenizer;import browser.json.itf.IBean;import freemarker.template.Configuration;import freemarker.template.DefaultObjectWrapper;import freemarker.template.Template;import freemarker.template.TemplateException;/** * * 模板工具类 * * @author hailang * @date 2009-7-9 上午10:21:25 * @version 1.0 */public class FreeMarkerUtil {public static void writeJavaBean(IBean bean) {Map<String, Object> root = new HashMap<String, Object>();root.put("bean", bean);FreeMarkerUtil.analysisTemplate("bean.ftl", "UTF-8", root);}/** * @author hailang * @date 2009-7-9 上午09:55:43 * @param templateName * 模板文件名称 * @param root * 数据模型根对象 * @param templateEncoding * 模板文件的编码方式 */private static void analysisTemplate(String templateName,String templateEncoding, Map<?, ?> root) {try {Configuration config = new Configuration();File file = new File("src/templates");config.setDirectoryForTemplateLoading(file);config.setObjectWrapper(new DefaultObjectWrapper());Template template = config.getTemplate(templateName,templateEncoding);Writer out = new OutputStreamWriter(new FileOutputStream(pathStr(root)), templateEncoding);template.process(root, out);} catch (IOException e) {e.printStackTrace();} catch (TemplateException e) {e.printStackTrace();}}private static String pathStr(Map<?, ?> map) {IBean bean = (IBean) map.get("bean");String packageStr = "src/" + bean.getPackageName();String className = firestUp(bean.getClassName());if (className.length() > 5) {if (className.substring(0, 5).equals("List<")) {className = className.substring(5, className.length() - 1);}}packageStr = packageStr.replace(".", "/");createFile(packageStr);return packageStr + "/" + className + ".java";}private static void createFile(String path) {StringTokenizer st = new StringTokenizer(path, "/");String path1 = st.nextToken() + "/";String path2 = path1;while (st.hasMoreTokens()) {path1 = st.nextToken() + "/";path2 += path1;File inbox = new File(path2);if (!inbox.exists())inbox.mkdir();}}public static String firestUp(String str) {String upperCase = str.toUpperCase();str = upperCase.substring(0, 1) + str.substring(1, str.length());return str;}public static String firestLow(String str) {String lowerCase = str.toLowerCase();str = lowerCase.substring(0, 1) + str.substring(1, str.length());return str;}}通过调用JSONBeanUtil的writeJsonBean()方法即可生成对应结构的javabean物理文件这些其实都没问题问题的关键在于,当我将json转bean(用的json-lib)的时候,JSONObject jo = JSONObject.fromObject(result.getResponse());Object bean = jo.toBean(jo, UserInitInfo.class, map);那个指定property类型的map我就实在不知道该怎么写了……因为很多重名对象,放map貌似不行……不知是我理解有错还是方式不对,还请各位赐教!在此先谢过大家了!!
解决方案
你写的确是很复杂换成Jackson试试用JsonNode(好像是这个),不管多复杂的JAVABEAN都能解析出来