JSON主要创建如下两种数据对象:
- 由JSON格式字符串创建,转换成JavaScript的Object对象;
- 由JSON格式字符串创建,转换成JavaScript的List或数组链表对象。
更多关于JSON的信息,请参考:JSON概述及其在JavaScript与Java中的应用(整理)
1. JSP页面中将对象转换为JSON字符串提交
1.1 创建JSP文件(convertObject2Json.jsp)
<%@ page language="java" import="java.util.*" pageEncoding="utf-8" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <script type="text/javascript" src="../../js/json2.js"> </script> <script type="text/javascript"> function ajaxTransferText(){ var BigText = document.getElementById("BigText").value; var ajaxTransferObjectRef = new ajaxTransferObject("张三", "密码11", 10, BigText); var JSONString = JSON.stringify(ajaxTransferObjectRef); if (window.ActiveXObject) { myAjaxObject = new ActiveXObject("Microsoft.XMLHTTP"); } else { myAjaxObject = new XMLHttpRequest(); } var urlString = "jsonString=" + JSONString; alert(urlString); myAjaxObject.open("POST", "postJson.action"+"?timestamp=" + new Date().getTime(), true); myAjaxObject.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); myAjaxObject.send(urlString); } function ajaxTransferObject(username, password, age, BigText){ this.username = username; this.password = password; this.age = age; this.BigText = BigText; } </script> </head> <body> <textarea name="textarea" id="BigText" cols="45" rows="5">需要提交的信息主体...</textarea> <br/> <input type="button" value="提交试试" onclick="ajaxTransferText()"/> </body> </html>
1.2 创建后台处理Action类
package com.clzhang.ssh.demo6; import net.sf.json.JSONObject; import com.opensymphony.xwork2.ActionSupport; /** * 获取前台提交的JSON数据 * @author Administrator * */ public class PostJSONAction extends ActionSupport { public static final long serialVersionUID = 1; private String jsonString; public String getJsonString() { return jsonString; } public void setJsonString(String jsonString) { this.jsonString = jsonString; } public String execute() { System.out.println(jsonString); JSONObject json = JSONObject.fromObject(jsonString); System.out.println("username=" + json.get("username")); System.out.println("username=" + json.get("password")); System.out.println("username=" + json.get("age")); System.out.println("username=" + json.get("BigText")); return null; } }
1.3 修改配置文件struts.xml
<action name="postJson" class="com.clzhang.ssh.demo6.PostJSONAction"> </action>
1.4 测试
打开IE,输入地址:http://127.0.0.1:8080/st/ssh/demo6/convertObject2Json.jsp
结果如下:
确定后,后台显示:
2. JSP页面获取后台Response返回的JSON对象
2.1 创建JSP文件(getJsonFromResp.jsp)
<%@ page language="java" import="java.util.*" pageEncoding="utf-8" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <script type="text/javascript" src="../../js/json2.js"> </script> <script type="text/javascript"> var myAjaxObject; //在List中存字符串 function getListString(){ if (window.ActiveXObject) { myAjaxObject = new ActiveXObject("Microsoft.XMLHTTP"); } else { myAjaxObject = new XMLHttpRequest(); } myAjaxObject.open("GET", "getJson!listString.action?date=" + new Date().getTime(), true); myAjaxObject.onreadystatechange = retrunListString; myAjaxObject.send(); } function retrunListString(){ if (myAjaxObject.readyState == 4) { if (myAjaxObject.status == 200) { var returnJSONString = myAjaxObject.responseText; var returnJSON = JSON.parse(returnJSONString); var showString = ""; for (var i = 0; i < returnJSON.length; i++) { showString = showString + returnJSON[i] + " "; } alert(showString); } } } //在List中存Bean function getListBean(){ if (window.ActiveXObject) { myAjaxObject = new ActiveXObject("Microsoft.XMLHTTP"); } else { myAjaxObject = new XMLHttpRequest(); } myAjaxObject.open("GET", "getJson!listBean.action?date=" + new Date().getTime(), true); myAjaxObject.onreadystatechange = retrunListBean; myAjaxObject.send(); } function retrunListBean(){ if (myAjaxObject.readyState == 4) { if (myAjaxObject.status == 200) { var returnJSONString = myAjaxObject.responseText; var returnJSON = JSON.parse(returnJSONString); var showString = ""; for (var i = 0; i < returnJSON.length; i++) { showString = showString + returnJSON[i].username + " " + returnJSON[i].password + " " + returnJSON[i].age + " " + returnJSON[i].createDate + "/n"; } alert(showString); } } } //在Map中存字符串 function getMapString(){ if (window.ActiveXObject) { myAjaxObject = new ActiveXObject("Microsoft.XMLHTTP"); } else { myAjaxObject = new XMLHttpRequest(); } myAjaxObject.open("GET", "getJson!mapString.action?date=" + new Date().getTime(), true); myAjaxObject.onreadystatechange = retrunMapString; myAjaxObject.send(); } function retrunMapString(){ if (myAjaxObject.readyState == 4) { if (myAjaxObject.status == 200) { var returnJSONString = myAjaxObject.responseText; var returnJSON = JSON.parse(returnJSONString); var showString = ""; for (var i in returnJSON[0]) { showString = showString + "key=" + i + " value=" + returnJSON[0][i] + "/n"; } alert(showString); } } } //在Map中存Bean function getMapBean(){ if (window.ActiveXObject) { myAjaxObject = new ActiveXObject("Microsoft.XMLHTTP"); } else { myAjaxObject = new XMLHttpRequest(); } myAjaxObject.open("GET", "getJson!mapBean.action?date=" + new Date().getTime(), true); myAjaxObject.onreadystatechange = retrunMapBean; myAjaxObject.send(); } function retrunMapBean(){ if (myAjaxObject.readyState == 4) { if (myAjaxObject.status == 200) { var returnJSONString = myAjaxObject.responseText; var returnJSON = JSON.parse(returnJSONString); var showString = ""; for (var i in returnJSON[0]) { showString = showString + "key=" + i + " username=" + returnJSON[0][i].username + " password=" + returnJSON[0][i].password + " age=" + returnJSON[0][i].age + " createDate=" + returnJSON[0][i].createDate + "/n"; } alert(showString); } } } </script> </head> <body> <input type="button" value="返回List中存String类型的JSON" onclick="getListString()"/> <br/> <br/> <input type="button" value="返回List中存Bean类型的JSON" onclick="getListBean()"/> <br/> <br/> <input type="button" value="返回Map中存String类型的JSON" onclick="getMapString()"/> <br/> <br/> <input type="button" value="返回Map中存Bean类型的JSON" onclick="getMapBean()"/> <br/> </body> </html>
2.2 创建后台处理Action类
package com.clzhang.ssh.demo6; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.*; import net.sf.json.JSONArray; import org.apache.struts2.ServletActionContext; import com.opensymphony.xwork2.ActionSupport; /** * 返回给前台JSON数据,以四种方式 * @author Administrator * */ public class ReturnJSONAction extends ActionSupport { public static final long serialVersionUID = 1; private List<String> lstString = new ArrayList<String>(); public ReturnJSONAction() { lstString.add("你今天吃了吗?"); lstString.add("吃了多吃点"); lstString.add("没吃回家吃去"); lstString.add("好好学习"); lstString.add("天天向上"); } public String listString() throws IOException { JSONArray json = JSONArray.fromObject(lstString); System.out.println(json.toString()); ServletActionContext.getResponse().setContentType("text/html"); ServletActionContext.getResponse().setCharacterEncoding("utf-8"); ServletActionContext.getResponse().getWriter().printf(json.toString()); ServletActionContext.getResponse().getWriter().flush(); ServletActionContext.getResponse().getWriter().close(); return null; } public String listBean() throws IOException { List<UserInfo> listBean = new ArrayList<UserInfo>(); for(String str: lstString) { UserInfo userInfo1 = new UserInfo(); userInfo1.setUsername(str); userInfo1.setPassword("P" + Math.random()); userInfo1.setAge((int)(Math.random()*10)); userInfo1.setCreateDate(new SimpleDateFormat("yyyy-MM-dd hh-mm-ss") .format(new Date())); listBean.add(userInfo1); } JSONArray json = JSONArray.fromObject(listBean); System.out.println(json.toString()); ServletActionContext.getResponse().setContentType("text/html"); ServletActionContext.getResponse().setCharacterEncoding("utf-8"); ServletActionContext.getResponse().getWriter().printf(json.toString()); ServletActionContext.getResponse().getWriter().flush(); ServletActionContext.getResponse().getWriter().close(); return null; } public String mapString() throws Exception { LinkedHashMap<String, String> mapString = new LinkedHashMap<String, String>(); int count = 1; for(String str: lstString) { mapString.put(""+count++, str+count); } JSONArray json = JSONArray.fromObject(mapString); System.out.println(json.toString()); ServletActionContext.getResponse().setContentType("text/html"); ServletActionContext.getResponse().setCharacterEncoding("utf-8"); ServletActionContext.getResponse().getWriter().printf(json.toString()); ServletActionContext.getResponse().getWriter().flush(); ServletActionContext.getResponse().getWriter().close(); return null; } public String mapBean() throws Exception { LinkedHashMap<String, UserInfo> mapString = new LinkedHashMap<String, UserInfo>(); int count = 1; for(String str: lstString) { UserInfo userInfo1 = new UserInfo(); userInfo1.setUsername(str); userInfo1.setPassword("P" + Math.random()); userInfo1.setAge((int)(Math.random()*10)); userInfo1.setCreateDate(new SimpleDateFormat("yyyy-MM-dd hh-mm-ss") .format(new Date())); mapString.put(""+count++, userInfo1); } JSONArray json = JSONArray.fromObject(mapString); System.out.println(json.toString()); ServletActionContext.getResponse().setContentType("text/html"); ServletActionContext.getResponse().setCharacterEncoding("utf-8"); ServletActionContext.getResponse().getWriter().printf(json.toString()); ServletActionContext.getResponse().getWriter().flush(); ServletActionContext.getResponse().getWriter().close(); return null; } public String execute() throws IOException { return null; } }
2.3 修改配置文件struts.xml
<action name="getJson" class="com.clzhang.ssh.demo6.ReturnJSONAction"> </action>
2.4 测试
打开IE,输入地址:http://127.0.0.1:8080/st/ssh/demo6/getJsonFromResp.jsp
2.4.1 按下“返回List中存String类型的JSON”按钮
2.4.2 按下“返回List中存Bean类型的JSON”按钮
2.4.3 按下“返回Map中存String类型的JSON”按钮
2.4.4 按下“返回Map中存Bean类型的JSON”按钮
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/7969.html