栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

JSON的使用

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

JSON的使用

1.JSON定义
是一种轻量级的数据交换格式

2.JSON作用
JSON 可以将 Javascript 对象中表示的一组数据转换为字符串,然后就可以在函数之间轻松地传递这个字符串,或者在异步应用程序中将字符串从 Web 客户机传递给服务器端程序。这个字符串看起来有点儿古怪,但是 Javascript 很容易解释它,而且 JSON 可以表示比"名称 / 值对"更复杂的结构。例如,可以表示数组和复杂的对象,而不仅仅是键和值的简单列表
3.为什么使用JSON
JSON采用完全独立于语言的文本格式,这些特性使JSON成为理想的数据交换语言。易于人阅读和编写,同时也易于机器解析和生成。
4.JSON语法 (0)JSON存储语法
数字(整数或浮点数)
字符串(在双引号中)
逻辑值(true 或 false)
数组(在中括号中)
对象(在大括号中)
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.JSON实战 4.1创建工程,数据库,导入jar包,js类库 4.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 findAll();
}
4.5FuritDaoImpl实现类
public class FruitDaoImpl extends baseDao implements FruitDao{
    @Override
    public List findAll() {
        ArrayList 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 findAll();
}
4.7FruitServiceImpl实现类
public class FruitServiceImpl implements FruitService{
    private FruitDao fruitDao = new FruitDaoImpl();
    @Override
    public List 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 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 list = fruitDao.findAll();
            StringBuffer json = new StringBuffer("[");
            for (int i=0;i list = fruitDao.findAll();
            String json = JSON.toJSonString(list);
            System.out.println(json);
            response.getWriter().print(json);
        }
    }
​
}
​
4.82 web.ml
    
        FruitServlet
        cn.kgc.servlet.FruitServlet
    
    
        FruitServlet
        /FruitServlet
    

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" %>
​

  
    $Title$
  
  
​
      
        
          
          
          
          
          
          
        
​
        
        
          
          
          
          
          
          
        
        
      
类别品种产地总重量(公斤)单价(元/公斤)操作
类别${fruit.}品种产地总重量(公斤)单价(元/公斤)操作
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" %>

  
    $Title$
    
    
  
  
      

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" %>

  
    $Title$
    
    
  
  
      
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" %>

  
    $Title$
    
    
  
  
      
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/592290.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号