AJAX004——基于JSON的数据交换
基于JSON的数据交换
-
如何创建json 对象以及如何访问
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>JSON</title> </head> <body> <script type="text/javascript"> //创建方式 var user = { "id": 1, "username": "张三", "age": 18, "address": "北京市", "hobbies": ["篮球", "足球", "游泳"], "currentResidence":{"city":"北京", "street":"西二旗"} } //访问方式一: console.log(user.id); console.log(user.username); console.log(user.age); console.log(user.address); console.log(user.hobbies[0]); console.log(user.hobbies[1]); console.log(user.hobbies[2]); console.log(user.currentResidence.city); console.log(user.currentResidence.street); //访问方式二: console.log(user["id"]); console.log(user["username"]); console.log(user["age"]); console.log(user["address"]); console.log(user["hobbies"][0]); console.log(user["hobbies"][1]); console.log(user["hobbies"][2]); console.log(user["currentResidence"]["city"]); console.log(user["currentResidence"]["street"]); </script> </body> </html>
-
从后端返回前端的是一个json格式的字符串,在WEB前端中,如何将这个字符串转换成json对象。
// "{\"username\" : \"zhangsan\", \"password\" : \"1233344\"}"从服务器返回的字符串 var jsonStr = "{\"username\" : \"zhangsan\", \"password\" : \"1233344\"}" //web前端内置的JSON对象 var jsonObj = JSON.parse(jsonStr) console.log(jsonObj.username) console.log(jsonObj.password)
-
在后端拼接JSON格式的字符串,响应给前端的浏览器(在线JSON校验格式化工具(Be JSON))
package com.zwm.ajax.web; import com.zwm.ajax.utils.DBUtil; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; @WebServlet("/ajaxservlet008") public class ajaxservlet008 extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/xml;charset=utf-8"); PrintWriter out = response.getWriter(); Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = DBUtil.getConnection(); String sql = "select * from stu"; preparedStatement = connection.prepareStatement(sql); resultSet = preparedStatement.executeQuery(); StringBuilder json = new StringBuilder(); json.append("["); while (resultSet.next()){ int id = resultSet.getInt("id"); String username = resultSet.getString("username"); int age = resultSet.getInt("age"); String address = resultSet.getString("address"); json.append("{\"id\":\""); json.append(id); json.append("\",\"username\":\""); json.append(username); json.append("\",\"age\":\""); json.append(age); json.append("\",\"address\":\""); json.append(address); json.append("\"},"); } json.append("]"); //去除最后一个元素后面的,号,不然格式不正确。 String str = json.toString(); char charToRemove = ','; int lastIndexOfChar = str.lastIndexOf(charToRemove); if (lastIndexOfChar != -1) { str = str.substring(0, lastIndexOfChar) + str.substring(lastIndexOfChar + 1); } out.print(str); } catch (Exception e) { e.printStackTrace(); }finally { DBUtil.close(connection,preparedStatement,resultSet); } } }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <input type="button" value="显示学员列表" id="btn"> <table border="1" width="50%"> <thead> <tr> <th>序号</th> <th>姓名</th> <th>年龄</th> <th>住址</th> </tr> </thead> <tbody id="stutbody"> </tbody> </table> <script type="text/javascript"> window.onload = function () { document.getElementById("btn").onclick = function () { var xhr = new XMLHttpRequest(); xhr.open("get", "/ajax001/ajaxservlet008", true); xhr.send(); xhr.onreadystatechange = function () { if(xhr.readyState == 4){ if(xhr.status == 200){ // document.getElementById("stutbody").innerHTML = xhr.responseText; //将json格式的数据转换为json对象 var stuList = JSON.parse(xhr.responseText);// 是一个json数组,并且数组中有多条数据。 var html = ""; for (var i = 0; i < stuList.length ; i++) { var stu = stuList[i]; html += "<tr>" ; html += "<td>" + stu.id + "</td>" ; html += "<td>" + stu.username + "</td>" ; html += "<td>" + stu.age + "</td>" ; html += "<td>" + stu.address + "</td>" ; html += "</tr>" ; } document.getElementById("stutbody").innerHTML = html; }else { alert(xhr.status); } } } } } </script> </body> </html>
-
拼接JSON格式的字符串太痛苦,可以使用阿里巴巴的fastjson组件,它可以将java对象转换成json格式的字符串
//fastjson初体验 package com.zwm.javaweb.json; import com.alibaba.fastjson.JSON; import java.util.ArrayList; import java.util.List; public class FastjsonTest { public static void main(String[] args) { User user = new User(1,"zhansan",23,"浙江嘉兴"); System.out.println(user); //将以上的User对象序列化成json字符串(使用阿里巴巴的fastjson组件中的JSON类即可。) //fastjson中有一个JSON类,类内部的方法都是静态的 String jsonStr = JSON.toJSONString(user); System.out.println(jsonStr); User user2 = new User(1,"zhansan2",23,"浙江嘉兴2"); User user3 = new User(1,"zhansan3",23,"浙江嘉兴3"); List<User> userList = new ArrayList<>(); userList.add(user); userList.add(user2); userList.add(user3); //将以上的User对象数组序列化成json字符串 String jsonStr2 = JSON.toJSONString(userList); System.out.println(jsonStr2); } }
项目优化
package com.zwm.ajax.web; import com.alibaba.fastjson.JSON; import com.zwm.ajax.pojo.User; import com.zwm.ajax.utils.DBUtil; import jakarta.servlet.ServletException; import jakarta.servlet.annotation.WebServlet; import jakarta.servlet.http.HttpServlet; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.PrintWriter; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.util.ArrayList; import java.util.List; @WebServlet("/ajaxservlet009") public class ajaxservlet009 extends HttpServlet { @Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/xml;charset=utf-8"); PrintWriter out = response.getWriter(); Connection connection = null; PreparedStatement preparedStatement = null; ResultSet resultSet = null; try { connection = DBUtil.getConnection(); String sql = "select * from stu"; preparedStatement = connection.prepareStatement(sql); resultSet = preparedStatement.executeQuery(); List<User> userList = new ArrayList<>(); while (resultSet.next()){ int id = resultSet.getInt("id"); String username = resultSet.getString("username"); int age = resultSet.getInt("age"); String address = resultSet.getString("address"); User user = new User(id,username,age,address); //借助fastjson组件,帮助我们生成json字符串。 userList.add(user); } out.print(JSON.toJSONString(userList)); } catch (Exception e) { e.printStackTrace(); }finally { DBUtil.close(connection,preparedStatement,resultSet); } } }
注意:web项目使用fastjson需要引入fastjson-1.2.2.jar,既将jar包放在lib目录下。