把HTML表格的内容保存为JSON格式以及JAVA后台解析全过程2

///将JSON对象转换成JAVA对象,且符合JAVABEAN规范
		public static List jsonToObject(String json, Object obj) throws Exception {
			// newJson:格式化后json
			String newJson = "";
			for (int i = 0; i < json.length(); i++) {
				if (json.charAt(i) != ' ' && json.charAt(i) != '"'
						&& json.charAt(i) != '\'' && json.charAt(i) != '\\') {
					newJson += json.charAt(i);
				}
			}

			int count = 0;
			String firstIndex = "";
			String secondIndex = "";
			for (int i = 0; i < newJson.length(); i++) {
				if (newJson.charAt(i) == '{') {
					count++;
					firstIndex += i + ",";
				}
				if (newJson.charAt(i) == '}') {
					secondIndex += i + ",";
				}
			}

			String[] strArr = new String[count];
			for (int i = 0; i < count; i++) {
				strArr[i] = newJson.substring(
						Integer.parseInt(firstIndex.substring(0,
								firstIndex.lastIndexOf(",")).split(",")[i]) + 1,
						Integer.parseInt(secondIndex.substring(0,
								secondIndex.lastIndexOf(",")).split(",")[i]));
			}

			String setMethodName = "";
			List list = new ArrayList();
			for (int i = 0; i < strArr.length; i++) {
				obj = obj.getClass().newInstance();
				for (int j = 0; j < strArr[i].split(",").length; j++) {
					setMethodName = "set"
							+ strArr[i].split(",")[j].substring(0,
									strArr[i].split(",")[j].indexOf("="))
									.substring(0, 1).toUpperCase()
							+ strArr[i].split(",")[j].substring(0,
									strArr[i].split(",")[j].indexOf("="))
									.substring(1);

					Method setMethod = obj.getClass().getMethod(
							setMethodName,
							new Class[] { SNCreateKitWareVoucherCmdImpl.getFieldType(
									strArr[i].split(",")[j].substring(0, strArr[i]
											.split(",")[j].indexOf("=")), obj) });
					setMethod.invoke(obj, new Object[] { strArr[i].split(",")[j]
							.substring(strArr[i].split(",")[j].indexOf("=") + 1) });
				}
				list.add(obj);
			}
			return list;
		}

		private static Class getFieldType(String fieldName, Object obj) {
			Field[] fields = obj.getClass().getDeclaredFields();
			for (int v = 0; v < fields.length; v++) {
				if (fieldName.equalsIgnoreCase(fields[v].getName())) {
					return fields[v].getType();
				}
			}
			return null;
		} 
 

你可能感兴趣的:(java,html,json)