将ajax传输的json转化为java的list<map>
Map<String, String> resultMap = new HashMap<String, String>(); request.setCharacterEncoding("UTF-8"); Map map = RequestUtil.reqToMap(request); String tc = map.get("tcdata").toString(); JSONArray array = JSONArray.fromObject(tc); List<Map<String, String>> tcList = new ArrayList<Map<String, String>>(); for (int i = 0; i < array.size(); i++) { JSONObject jsonObject = array.getJSONObject(i); Map<String, String> map1 = new HashMap<String, String>(); for (Iterator<?> iter = jsonObject.keys(); iter.hasNext(); ) { String key = (String) iter.next(); String value = jsonObject.get(key).toString(); map1.put(key, value); } tcList.add(map1); }
return tcList;
public class RequestUtil { @SuppressWarnings("unchecked") public static HashMap reqToMap(HttpServletRequest req) throws Exception { try { HashMap hmReq = new HashMap(); String fieldName = null; String fieldValue = null; //add parameters and values to hdReq Enumeration paras = req.getParameterNames(); while (paras.hasMoreElements()) { fieldName = (String) paras.nextElement(); fieldValue = (String) req.getParameter(fieldName); if (fieldValue != null) { hmReq.put(fieldName.toLowerCase(), fieldValue); } } return hmReq; } catch (Exception e) { throw e; } }}
也可以用流的方式来处理:
Map<String, String> resultMap = new HashMap<String, String>(); StringBuffer stringBuffer = new StringBuffer(); String mbl = "";//提单号 try { BufferedReader in = new BufferedReader(new InputStreamReader(request.getInputStream())); String inputLine = null; while ((inputLine = in.readLine()) != null) { stringBuffer.append(new String(inputLine.getBytes(), "utf-8")); } //关闭连接 in.close(); String dataStr = stringBuffer.toString(); // 将json字符串转换为json对象 JSONObject jsonObj = JSONObject.fromObject(dataStr); Object tcdataJson = jsonObj.get("tcdata"); if (tcdataJson == null || JSONArray.fromObject(tcdataJson.toString()).size() < 1) { resultMap.put("result", "fail"); resultMap.put("reason", "传入的主要数据为空,请重新发送"); } else {