JSON与Java对象的互相转换
-
例一(单个对象进行赋值):
@RequestMapping("test1.do") @ResponseBody public JSONObject test1(HttpServletRequest request, HttpServletResponse response) { JSONObject jsonObject = new JSONObject(); jsonObject.put("key1", "value1"); jsonObject.put("key2", "value2"); jsonObject.put("key3", "value3"); return jsonObject; }
-
例二(多个对象进行转换):
@RequestMapping("TestListQrcode.do") @ResponseBody public JSONObject TestListQrcode(HttpServletRequest request, HttpServletResponse response) throws Exception { //String user_phone = request.getParameter("user_phone"); String user_phone ="13652458975"; Qrcode qrcode = new Qrcode(); qrcode.setUser_phone(user_phone); qrcode.setQrcode_type("普通型"); List<Qrcode> list = qrcodeService.selectQrcodeList(qrcode); //创建json集合 //用的包:import net.sf.json.JSONArray; JSONArray jsonArray = JSONArray.fromObject(list); System.out.println(jsonArray.toString()); JSONObject jsonObject = new JSONObject(); jsonObject.put("code", 1); jsonObject.put("data", jsonArray.toString()); return jsonObject; }
-
例三(字符串的拼接,我只在servlet中用过):
String value1 = "1"; int value2 = count-1; System.out.println("给前面传的count:"+value2); String photo_file = par[0] + "/" + par[1] + "/images"; //进行拼凑json字符串 String jsonStr = "{" + '"'+ "success" + '"' +":" + '"' + value1 + '"' + "," + '"' + "count" + '"' +":" + '"' + value2 + '"' + "," + '"' + "photo_file" + '"' +":" + '"' + photo_file + '"' +"}" ; PrintWriter out =null ; out =response.getWriter() ; out.write(jsonStr); out.close();