json 应用实例
- <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
- <html>
- <head>
- <title>JSON学习</title>
- <meta http-equiv="pragma" content="no-cache">
- <meta http-equiv="cache-control" content="no-cache">
- <meta http-equiv="expires" content="0">
- <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
- <meta http-equiv="description" content="This is my page">
- <script type="text/javascript" src="js/json.js"></script>
- </head>
- <script language="javascript">
- var xmlHttp;
- function createXMLHttpRequest() {
- if (window.ActiveXObject) {
- xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
- }
- else if (window.XMLHttpRequest) {
- xmlHttp = new XMLHttpRequest();
- }
- }
- function doJSON(){
- var car = getCarObject();
- //将JS对象转化成JSON格式的Text
- var carAsJSON = JSON.stringify(car);
- alert(carAsJSON);
- var url = "JsonTest1?timeStamp="+new Date().getTime();
- createXMLHttpRequest();
- xmlHttp.open("POST", url, true);
- xmlHttp.onreadystatechange = handleStateChange;
- xmlHttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
- xmlHttp.send(carAsJSON);
- }
- //Ajax的回调方法
- function handleStateChange(){
- if(xmlHttp.readyState == 4){
- if(xmlHttp.status == 200){
- parseResults();
- }
- }
- }
- //具体的回调作动
- function parseResults(){
- var responseDiv = document.getElementById("serverResponse");
- if(responseDiv.hasChildNodes()){
- responseDiv.removeChild(responseDiv.childNodes[0]);
- }
- //xmlHttp.responseText是servlet中返回回来的JSON格式的数据,将它创建成一个js的node对象放到DIV中
- var responseText = document.createTextNode(xmlHttp.responseText);
- responseDiv.appendChild(responseText);
- //将json格式的Text转化成JSON对象:用eval(‘(‘+response+‘)‘)
- var resultJson = eval(‘(‘+xmlHttp.responseText+‘)‘);
- alert(resultJson);
- alert(resultJson.make);
- alert(resultJson.model);
- alert(resultJson.year);
- alert(resultJson.color);
- }
- //JS中的一个对象
- function Car(make,model,year,color){
- this.make = make;
- this.model = model;
- this.year = year;
- this.color = color;
- }
- //构成对象并返回
- function getCarObject(){
- return new Car("Dodge", "Coronet R/T", 1968, "yellow");
- }
- </script>
- <body>
- <form action="#">
- <input type="button" value="Click here to send JSON data to the server" onclick="doJSON();"/>
- </form>
- <h2>Server Response:</h2>
- <div id="serverResponse">
- </div>
- </body>
- </html>
在我的servlet中实现如下:
- public class JsonTest1 extends HttpServlet {
- /**
- *
- */
- private static final long serialVersionUID = 306348969081510518L;
- public void doGet(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- this.doPost(request, response);
- }
- public void doPost(HttpServletRequest request, HttpServletResponse response)
- throws ServletException, IOException {
- String json = readJSONStringFromRequestBody(request);
- System.out.println("json = " + json);
- //将request中接收的字符串转化成json对java对象
- JSONObject jsonObject = JSONObject.fromObject(json);
- System.out.println("jsonObject = " + jsonObject.toString());
- System.out.println(jsonObject.getInt("year"));
- System.out.println(jsonObject.getString("make"));
- System.out.println(jsonObject.getString("model"));
- System.out.println(jsonObject.getString("color"));
- //设置返回的格式是text
- response.setContentType("text/plain");
- response.getWriter().print(jsonObject);
- }
- private String readJSONStringFromRequestBody(HttpServletRequest request) {
- StringBuffer json = new StringBuffer();
- String line = null;
- try {
- BufferedReader bufferRead = request.getReader();
- while ((line = bufferRead.readLine()) != null) {
- System.out.println("line = " + line);
- json.append(line);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- return json.toString();
- }
- }
servlet的配置如下:
- <servlet>
- <servlet-name>JsonTest1</servlet-name>
- <servlet-class>com.mengya.servlet.JsonTest1</servlet-class>
- </servlet>
- <servlet-mapping>
- <servlet-name>JsonTest1</servlet-name>
- <url-pattern>/JsonTest1</url-pattern>
- </servlet-mapping>
相于java对象与json之类的转化的一些测试如下(跟上面的实例无关):
- public class JsonBean1 {
- private String col;
- private String row;
- private String value;
- public String getCol() {
- return col;
- }
- public void setCol(String col) {
- this.col = col;
- }
- public String getRow() {
- return row;
- }
- public void setRow(String row) {
- this.row = row;
- }
- public String getValue() {
- return value;
- }
- public void setValue(String value) {
- this.value = value;
- }
- }
- /**
- *
- * @author 张明学
- *
- */
- public class JsonBanTest {
- /**
- * @param args
- */
- public static void main(String[] args) {
- boolean[] boolArray = new boolean[] { true, false, true };
- JSONArray jsonArray1 = JSONArray.fromObject(boolArray);
- System.out.println(jsonArray1);
- List list = new ArrayList();
- list.add("first");
- list.add("second");
- JSONArray jsonArray2 = JSONArray.fromObject(list);
- System.out.println(jsonArray2);
- JSONArray jsonArray3 = JSONArray.fromObject("[‘json‘,‘is‘,‘easy‘]");
- System.out.println(jsonArray3);
- Map map = new HashedMap();
- map.put("name", "json");
- map.put("bool", Boolean.TRUE);
- map.put("int", new Integer(1));
- map.put("arr", new String[] { "a", "b" });
- map.put("func", "function(i){return this.arr[i]}");
- JSONObject json = JSONObject.fromObject(map);
- System.out.println(json);
- JsonBean1 jb = new JsonBean1();
- jb.setCol("col1");
- jb.setRow("row1");
- jb.setValue("123");
- JSONObject ja = JSONObject.fromObject(jb);
- System.out.println(ja.toString());
- List list2 = new ArrayList();
- JsonBean1 jb2 = new JsonBean1();
- jb2.setCol("col1");
- jb2.setRow("row1");
- jb2.setValue("123");
- list2.add(jb);
- list2.add(jb2);
- JSONArray jsonArray = JSONArray.fromObject(list2);
- System.out.println(jsonArray.toString());
- String jsonStr = "{name=\"json\",bool:true,int:1,double:2.2,func:function(a){ return a; },array:[1,2]}";
- JSONObject jsonObject = JSONObject.fromObject(jsonStr);
- System.out.println(jsonObject);
- System.out.println(jsonObject.get("name"));
- System.out.println(jsonObject.get("bool"));
- System.out.println(jsonObject.get("int"));
- System.out.println(jsonObject.get("double"));
- System.out.println(jsonObject.get("func"));
- System.out.println(jsonObject.get("array"));
- }
- }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。