使用 JSON 需要的 jar 包:
建议:
日期 直接转 json 会报错,一般把日期转换成字符串 再转json ,取的时候取的是字符串,再根据格式转换为 date 类型
一.json List 互转:
1.List 转 Json
ArrayList<ScheduleModel> al=new ArrayList<ScheduleModel>(); JSONArray jsonArray = JSONArray.fromObject(al); String jsonJAVA = jsonArray.toString(); //以字符流的方式,将json字符串输出到客户端 response.setContentType("text/html;charset=UTF-8"); PrintWriter pw = response.getWriter(); pw.write(jsonJAVA); pw.flush(); pw.close();
2.Json 格式字符串 转 List
JSONArray data = JSONArray.fromObject(str); ArrayList<ScheduleModel> scheduleList = new ArrayList<ScheduleModel>(); for(int i=0;i<data.size();i++){ //封装 bean JSONObject jobj = (JSONObject) data.get(i); ScheduleModel bean = new ScheduleModel(); bean.setScheduleId(Integer.parseInt(jobj.get("scheduleId").toString())); bean.setHspId(jobj.get("hspId").toString()); bean.setHspName(jobj.get("hspName").toString()); bean.setInnerOfficeId(jobj.get("innerOfficeId").toString()); bean.setInnerOfficeName(jobj.get("innerOfficeName").toString()); bean.setDocId(jobj.get("docId").toString()); bean.setDocName(jobj.get("docName").toString()); bean.setDocGra(jobj.get("docGra").toString()); bean.setNoonCode(jobj.get("noonCode").toString()); bean.setResidueNum(Integer.parseInt(jobj.get("residueNum").toString())); //日期转换 String strDate = jobj.get("visitDate").toString(); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); Date date = sdf.parse(strDate); bean.setVisitDate(date); scheduleList.add(bean); }
二. map json 互转
1.map 转 Json ,分页显示的时候可能用到
//调用业务层 DoctorService docService= factory.DaoFactory.getDoctorServiceInstanse(); Page page = docService.show(currPageNO); //创建Map集合 Map<String,Object> map = new LinkedHashMap<String,Object>(); map.put("total",page.getAllRecordNO()); map.put("rows",page.getDocList()); //使用第三方工具将map转成json文本 JSONArray jsonArray = JSONArray.fromObject(map); String jsonJAVA = jsonArray.toString(); //去掉二边的空格 jsonJAVA = jsonJAVA.substring(1,jsonJAVA.length()-1); System.out.println("jsonJAVA=" + jsonJAVA); //以字符流的方式,将json字符串输出到客户端 response.setContentType("text/html;charset=UTF-8"); PrintWriter pw = response.getWriter(); pw.write(jsonJAVA); pw.flush(); pw.close();