- 例一(單個對象進行指派):
@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();