JSON教程

1.JSON定义

是一种轻量级的数据交换格式
通过JSON直接返回数据给前端

2.JSON作用

JSON 可以将 JavaScript 对象中表示的一组数据转换为字符串,然后就可以在函数之间轻松地传递这个字符串,或者在异步应用程序中将字符串从 Web 客户机传递给服务器端程序。这个字符串看起来有点儿古怪,但是 JavaScript 很容易解释它,而且 JSON 可以表示比"名称 / 值对"更复杂的结构。例如,可以表示数组和复杂的对象,而不仅仅是键和值的简单列表
1.Json用来在客户端和服务器端转换数据用的。
2.Json的键值对格式容易让js解析
3.Json的键值对格式可以在ajax返回函数中被转换或者解析
 

3.为什么使用JSON

JSON采用完全独立于语言的文本格式,这些特性使JSON成为理想的数据交换语言。易于人阅读和编写,同时也易于机器解析和生成。
1.独立于任何语言
2.易于人理解
3.便于机器解析和创建

4.JSON语法


    (0)JSON存储语法

数字(整数或浮点数)

字符串(在双引号中)

逻辑值(true 或 false)

数组(在中括号中)

对象(在大括号中)

null
例子:
{"age":123}
{"name":"zs"}
("flag":true}
[("name":"zs"},i "age":123}]
{"pwd":"123"}
{"pwd":null}

    (1)JSON数字(常用)

JSON 数字可以是整型或者浮点型

{ "age":30 }

    (2)JSON对象(常用)

{ "name":"kgc" , "pwd":"23434" }

    (3)JSON数组(常用)

[

        { "name":"菜鸟教程" , "url":"www.runoob.com" }, 

        { "name":"google" , "url":"www.google.com" }, 

        { "name":"微博" , "url":"www.weibo.com" }

]

4.2JSON实战

        4.2.1创建工程,数据库,导入jar包,js类库
        4.2.2创建实体类

public class Fruit {
    private Integer fruitId;
    private String type;
    private String breed;
    private String area;
    private String brief;
    private Integer weight;
    private BigDecimal price;
 
    public Fruit() {
    }
 
    public Fruit(Integer fruitId, String type, String breed, String area, String brief, Integer weight, BigDecimal price) {
        this.fruitId = fruitId;
        this.type = type;
        this.breed = breed;
        this.area = area;
        this.brief = brief;
        this.weight = weight;
        this.price = price;
    }
 
    public Integer getFruitId() {
        return fruitId;
    }
 
    public void setFruitId(Integer fruitId) {
        this.fruitId = fruitId;
    }
 
    public String getType() {
        return type;
    }
 
    public void setType(String type) {
        this.type = type;
    }
 
    public String getBreed() {
        return breed;
    }
 
    public void setBreed(String breed) {
        this.breed = breed;
    }
 
    public String getArea() {
        return area;
    }
 
    public void setArea(String area) {
        this.area = area;
    }
 
    public String getBrief() {
        return brief;
    }
 
    public void setBrief(String brief) {
        this.brief = brief;
    }
 
    public Integer getWeight() {
        return weight;
    }
 
    public void setWeight(Integer weight) {
        this.weight = weight;
    }
 
    public BigDecimal getPrice() {
        return price;
    }
 
    public void setPrice(BigDecimal price) {
        this.price = price;
    }
}

4.3BaseDao工具类

package cn.kgc.dao;
 
import java.sql.*;
 
/**
 * 连接数据库的工具类
 */
public class BaseDao {
//    1.定义连接对象
    protected static Connection conn;
//    2.定义预编译对象
    protected static PreparedStatement ps;
//    3.定义结果集对象
    protected static ResultSet rs;
 
    //4.定义连接数据库的方法getConn()
    public static void getConn(){
        try {
            //5.注册驱动
            Class.forName("com.mysql.jdbc.Driver");
            //6.管理连接
            conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/db_fruit","root","ok");
            //7.测试连接对象
            System.out.println(conn);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
 
    //8.定义关闭连接数据库方法closeAll()
    public static void closeAll(){
        try {
            //9.关闭结果集对象
            if(rs!=null){
                rs.close();
            }
            //10.关闭预编译对象
            if(ps!=null){
                ps.close();
            }
            //11.关闭连接对象
            if(conn!=null){
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
 //12.定义增删改的通用方法executeUpdate()
    public int executeUpdate(String sql,Object[] params){
        int flag = 0;
        //13.调用连接数据库的方法
        getConn();
        try {
            //14.调用prepareStatement(),发送sql语句给数据库
            ps = conn.prepareStatement(sql);
            if(params!=null){
                //15.循环将方法中的参数塞入结果集中
                for (int i = 0; i < params.length; i++) {
                    ps.setObject(i+1,params[i]);
                }
            }
            //16.执行处理(增删改)的方法
            flag = ps.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally{
            closeAll();
        }
        return flag;
    }
 
    //17.定义通用的查询方法executeQuery()
    public ResultSet executeQuery(String sql,Object[] params){
        //18.连接数据库
        getConn();
        try {
            //19.执行prepareStatement()发送sql语句到数据库
            ps = conn.prepareStatement(sql);
            if(params!=null){
                //20.循环遍历参数,将参数塞入结果集中(所谓的?)
                for (int i = 0; i < params.length; i++) {
                    ps.setObject(i+1,params[i]);
                }
            }
            //21.执行处理(查询)的方法
            rs = ps.executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return rs;
    }
 
    //22.入口函数的测试
    public static void main(String[] args) {
        getConn();
    }
 
}

4.4FruitDao接口

public interface FruitDao {
    public List<Fruit> findAll();
}

4.5FuritDaoImpl实现类

public class FruitDaoImpl extends BaseDao implements FruitDao{
    @Override
    public List<Fruit> findAll() {
        ArrayList<Fruit> list = new ArrayList<>();
        rs = super.executeQuery("select * from FRUIT", null);
        try {
            while(rs.next()){
                Fruit fruit = new Fruit(rs.getInt("FRUIT_ID"), rs.getString("TYPE"),rs.getString("BREED"),rs.getString("AREA"),rs.getString("BRIEF"),rs.getInt("WEIGHT"),rs.getBigDecimal("PRICE"));
                list.add(fruit);
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }finally {
            super.closeAll();
        }
        return list;
    }
}

4.6FruitService接口

public interface FruitService {
    public List<Fruit> findAll();
}

4.7FruitServiceImpl实现类

public class FruitServiceImpl implements FruitService{
    private FruitDao fruitDao = new FruitDaoImpl();
    @Override
    public List<Fruit> findAll() {
        return fruitDao.findAll();
    }
}

4.8FruitServlet

package cn.kgc.servlet;
 
import cn.kgc.dao.FruitDaoImpl;
import cn.kgc.entity.Fruit;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
 
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.util.List;
 
public class FruitServlet extends HttpServlet {
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String action = request.getParameter("action");
        FruitDaoImpl fruitDao = new FruitDaoImpl();
        if(action.equals("list")){
            List<Fruit> list = fruitDao.findAll();
            request.setAttribute("list",list);
            request.getRequestDispatcher("list.jsp").forward(request,response);
        }else if(action.equals("listRspJSON")){
            String json = "[{\"fruitId\":\"11\",\"type\":\"www\",\"breed\":\"32323\"},{\"fruitId\":\"2\",\"type\":\"zzz\",\"breed\":\"dd\"},{\"fruitId\":\"3\",\"type\":\"aaa\",\"breed\":\"vvv\"}]";
            response.getWriter().print(json);
        }else if(action.equals("listJSON")){
            List<Fruit> list = fruitDao.findAll();
            StringBuffer json = new StringBuffer("[");
            for (int i=0;i<list.size();i++){
                Fruit fruit = list.get(i);
                String fruitId = (fruit.getFruitId() + "").replace("\"", "");
                String type = (fruit.getType() + "").replace("\"", "");
                String breed = (fruit.getBreed() + "").replace("\"", "");
                String fruitStr = "{\"fruitId\":\""+fruitId+"\",\"type\":\""+type+"\",\"breed\":\""+breed+"\"}";
                json.append(fruitStr);
                if(i<list.size()-1){
                    json.append(",");
                }
            }
            json.append("]");
            System.out.println(json);
            //[{"fruitId":"1","type":"dfsa","breed":"32323"},{"fruitId":"2","type":"zzz","breed":"dd"},{"fruitId":"3","type":"aaa","breed":"vvv"}]
            response.getWriter().print(json);
        }else if(action.equals("listFastJSON")){
            List<Fruit> list = fruitDao.findAll();
            String json = JSON.toJSONString(list);
            System.out.println(json);
            response.getWriter().print(json);
        }
    }
 
}

4.82 web.ml

<servlet>
        <servlet-name>FruitServlet</servlet-name>
        <servlet-class>cn.kgc.servlet.FruitServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>FruitServlet</servlet-name>
        <url-pattern>/FruitServlet</url-pattern>
    </servlet-mapping>

4.9list.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: haohao
  Date: 2021/11/3
  Time: 12:06
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
 
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
 
      <table>
        <tr>
          <td>类别</td>
          <td>品种</td>
          <td>产地</td>
          <td>总重量(公斤)</td>
          <td>单价(元/公斤)</td>
          <td>操作</td>
        </tr>
 
        <c:forEach items="${list}" var="fruit">
        <tr>
          <td>类别${fruit.}</td>
          <td>品种</td>
          <td>产地</td>
          <td>总重量(公斤)</td>
          <td>单价(元/公斤)</td>
          <td>操作</td>
        </tr>
        </c:forEach>
      </table>
  </body>
</html>

4.10listRspJSON.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: haohao
  Date: 2021/11/3
  Time: 12:06
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
    <script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
    <script>
      $(function(){
        $.ajax({
          url:"FruitServlet",
          type:"post",
          data:{"action":"listRspJSON"},
          dataType:"json",
          success:function(data){
            var $ul = $("table");
            $ul.append("<tr><td>编号</td><td>类型</td><td>种类</td></tr>");
            for(var i=0;i<data.length;i++){
              $ul.append("<tr><td>"+data[i].fruitId+"<td>"+data[i].type+"</td><td>"+data[i].breed+"</td></tr>");
            }
          },
          error:function(){}
        });
      });
    </script>
  </head>
  <body>
      <table border="1"></table>
  </body>
</html>

4.11listJson.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: haohao
  Date: 2021/11/3
  Time: 12:06
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
    <script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
    <script>
      $(function(){
        $.ajax({
          url:"FruitServlet",
          type:"post",
          data:{"action":"listJSON"},
          dataType:"json",
          success:function(data){
            var $ul = $("table");
            $ul.append("<tr><td>编号</td><td>类型</td><td>种类</td></tr>");
            for(var i=0;i<data.length;i++){
              $ul.append("<tr><td>"+data[i].fruitId+"<td>"+data[i].type+"</td><td>"+data[i].breed+"</td></tr>");
            }
          },
          error:function(){}
        });
      });
    </script>
  </head>
  <body>
      <table border="1"></table>
  </body>
</html>

4.11 listFastJson.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--
  Created by IntelliJ IDEA.
  User: haohao
  Date: 2021/11/3
  Time: 12:06
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
    <script type="text/javascript" src="js/jquery-1.12.4.min.js"></script>
    <script>
      $(function(){
        $.ajax({
          url:"FruitServlet",
          type:"post",
          data:{"action":"listFastJSON"},
          dataType:"json",
          success:function(data){
            var $ul = $("table");
            $ul.append("<tr><td>编号</td><td>类型</td><td>种类</td></tr>");
            for(var i=0;i<data.length;i++){
              $ul.append("<tr><td>"+data[i].fruitId+"<td>"+data[i].type+"</td><td>"+data[i].breed+"</td></tr>");
            }
          },
          error:function(){}
        });
      });
    </script>
  </head>
  <body>
      <table border="1"></table>
  </body>
</html>

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值