素材巴巴 > 程序开发 >

【第49天】JSON的创建(封装)方法、传输格式以及应用

程序开发 2023-09-03 12:37:43
  • 2 AJAX和原生JS通过JSON传输实现级联两个组件

  • 1 JSON

           JSON(JavaScript Object Notation,JS对象表示法),一种轻量级的数据交换格式。2004年诞生,2006年加入的ajax技术体系,用来取代xml封装批量的数据,本质上就是一个特殊格式的字符串,可以直接打印。被称之为Java的第十种数据类型。

    1.1 两种传输格式

    1.2 三种创建(封装)方法

           JSON存在三种封装方式,可以封装成以上两种格式的JSON数据。

    package com.test.test;import com.test.po.Student;
     import net.sf.json.JSONArray;
     import net.sf.json.JSONObject;
     import net.sf.json.JsonConfig;import java.util.*;public class Test {public static void main(String[] args) {//1)可以封装任意格式的数据,封装之后呈现格式1的JSON//但这样的格式在存入JSON时存放了一些key值,这些值很多情况下都是垃圾数据int i = 3;String str = "测试JSON方法1";boolean flag = true;String[] strArray = {"Java", "C++", "Python"};JSONObject jo = new JSONObject();jo.put("key1", i);jo.put("key2", str);jo.put("key3", flag);jo.put("key4", strArray);jo.put("key5", new Student(1, "张三", "1@t.tt", "111222"));System.out.println(jo);//输出{"key1":3,"key2":"测试JSON方法1","key5":{"phone":"111222","name":"张三","id":1,"isdeleted":0,"email":"1@t.tt"},//"key3":true,"key4":["Java","C++","Python"]}//2)可以封装自定义数据类型和Map,封装之后呈现格式1的JSONMap map = new HashMap<>();map.put(1, "VUE");map.put(2, "React");map.put(3, "Angular");map.put(4, "jQuery");//存MapJSONObject js1 = JSONObject.fromObject(map);System.out.println(js1);//输出{"1":"VUE","2":"React","3":"Angular","4":"jQuery"}//存自定义数据类型JSONObject js2 = JSONObject.fromObject(new Student(2, "李四", "2@t.tt", "111223"));System.out.println(js2);//输出{"phone":"111223","name":"李四","id":2,"isdeleted":0,"email":"2@t.tt"}//有选择地对自定义数据类型中的属性封装JsonConfig jc = new JsonConfig();//将不需要封装的属性列出jc.setExcludes(new String[]{"id", "name", "phone"});JSONObject js3 = JSONObject.fromObject(new Student(3, "王五", "3@t.tt", "111224"), jc);System.out.println(js3);//输出{"isdeleted":0,"email":"3@t.tt"}//3)专门用来封装List、数组和Set,封装之后呈现格式2的JSON//String[] strArray = {"Java", "C++", "Python"};JSONArray ja1 = JSONArray.fromObject(strArray);System.out.println(ja1);//输出["Java","C++","Python"]List list = new ArrayList<>();list.add("HTML5");list.add("CSS3");list.add("JS6");JSONArray ja2 = JSONArray.fromObject(list);System.out.println(ja2);//输出["HTML5","CSS3","JS6"]Set set = new HashSet<>();set.add("山东鲁能");set.add("广州恒大");set.add("上海申花");set.add("大连一方");JSONArray ja3 = JSONArray.fromObject(set);System.out.println(ja3);//输出["广州恒大","上海申花","山东鲁能","大连一方"]}
     }
     

    2 AJAX和原生JS通过JSON传输实现级联两个组件

          使用AJAX和原生的JS实现下拉列表选中省份(直辖市)时,市(区)自动出现在右边的下拉列表中。

    package com.test.dao;import com.test.factory.Factory;
     import com.test.po.City;
     import com.test.po.Province;
     import org.apache.commons.dbutils.QueryRunner;
     import org.apache.commons.dbutils.handlers.BeanListHandler;import java.sql.Connection;
     import java.util.List;public class ProvinceCityDaoImpl implements ProvinceCityDaoIf{Connection conn;QueryRunner qr = new QueryRunner();/*** 拿取全部省份 省份字段:id name*/@Overridepublic List queryProvince() {try {String sql = "select * from province";conn = Factory.getCon();return qr.query(conn, sql, new BeanListHandler(Province.class));} catch (Exception e) {e.printStackTrace();return null;}}/*** 根据pid拿取城市 城市字段:id name pid(省份表的id)** @param pid*/@Overridepublic List queryCityByPid(Integer pid) {try {String sql = "select * from city where pid = ?";conn = Factory.getCon();return qr.query(conn, sql, new BeanListHandler(City.class), pid);} catch (Exception e) {e.printStackTrace();return null;}}
     }
     

    cascade.html

    
     级联
     
     

    编写Servlet类,接收请求并返回省份的数据

    package com.test.servlet;import com.test.dao.ProvinceCityDaoIf;
     import com.test.dao.ProvinceCityDaoImpl;
     import com.test.po.Province;
     import net.sf.json.JSONObject;import javax.servlet.ServletException;
     import javax.servlet.http.HttpServlet;
     import javax.servlet.http.HttpServletRequest;
     import javax.servlet.http.HttpServletResponse;
     import java.io.IOException;
     import java.io.PrintWriter;
     import java.util.List;public class ShowProvince extends HttpServlet {protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("utf-8");response.setContentType("text/plain;charset=utf-8");PrintWriter out = response.getWriter();ProvinceCityDaoIf dao = new ProvinceCityDaoImpl();//拿取全部省份List list = dao.queryProvince();//第一种封装方法JSONObject jo = new JSONObject();jo.put("province", list);System.out.println(jo);out.print(jo);out.close();}
     }
     

    效果图:
    在这里插入图片描述

    向cascade.html中追加

     function showCity(pid){create();//这里选用一次GET请求方式//使用get时需要后面new一个Date(),//因为是明文传输,浏览器的地址栏可能会有缓存之前的数据,//所以要加一个每次都不一样的时间,即new Date(),防止浏览器使用之前的缓存发送请求//另外,get默认是字符流,不需要定义字符集Content-Typerequest.open("get", "showCity?pid=" + pid + "&time=" + new Date(), true);request.onreadystatechange = function(){if(request.readyState==4){if(request.status == 200){//当选中的为山东省let text = request.responseText;//[{"name":"济南","pid":1,"id":1},// {"name":"青岛","pid":1,"id":2},// {"name":"淄博","pid":1,"id":3},// {"name":"枣庄","pid":1,"id":4},// {"name":"烟台","pid":1,"id":5},// {"name":"潍坊","pid":1,"id":6},// {"name":"济宁","pid":1,"id":7},// {"name":"泰安","pid":1,"id":8}]//使用第三种封装方式,可以省一步,数组不需要再转类型let array = JSON.parse(text);//(8) [{…}, {…}, {…}, {…}, {…}, {…}, {…}, {…}]//0: {name: "济南", pid: 1, id: 1}//1: {name: "青岛", pid: 1, id: 2}//2: {name: "淄博", pid: 1, id: 3}//3: {name: "枣庄", pid: 1, id: 4}//4: {name: "烟台", pid: 1, id: 5}//5: {name: "潍坊", pid: 1, id: 6}//6: {name: "济宁", pid: 1, id: 7}//7: {name: "泰安", pid: 1, id: 8}//拿取城市下拉列表框let dom_select = document.getElementById("city");//以防城市的列表框切换后还留存上一次的数据,//向其中加入数据,若原来的省份对应的城市数量多于这次的数量,//会出现两个省份的城市混排的现象while(dom_select.length > 1){dom_select.removeChild(dom_select.item(1));}for(let i = 0; i < array.length; i++){let city = array[i];let id = city.id;let name = city.name;dom_select.options[i + 1] = new Option(name, id);}}}};request.send(null);}
     

    编写Servlet类,按接收GET请求的参数返回城市的数据

    package com.test.servlet;import com.test.dao.ProvinceCityDaoIf;
     import com.test.dao.ProvinceCityDaoImpl;
     import net.sf.json.JSONArray;import javax.servlet.ServletException;
     import javax.servlet.http.HttpServlet;
     import javax.servlet.http.HttpServletRequest;
     import javax.servlet.http.HttpServletResponse;
     import java.io.IOException;
     import java.io.PrintWriter;public class ShowCity extends HttpServlet {protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("utf-8");response.setContentType("text/plain;charset=utf-8");ProvinceCityDaoIf dao = new ProvinceCityDaoImpl();//使用第三种封装方式JSONArray ja = JSONArray.fromObject(dao.queryCityByPid(Integer.parseInt(request.getParameter("pid"))));PrintWriter out = response.getWriter();out.print(ja);System.out.println(ja);out.close();}
     }
     

    效果图:
    在这里插入图片描述


    标签:

    素材巴巴 Copyright © 2013-2021 http://www.sucaibaba.com/. Some Rights Reserved. 备案号:备案中。