zoukankan      html  css  js  c++  java
  • Json详解

    Json详解

    Json是一种轻量级的数据交换格式,采用一种“键:值”对的文本格式来存储和表示数据,在系统交换数据过程中常常被使用,是一种理想的数据交换语言。在使用JavaWeb开发时,不可避免的会遇到Json的使用。

    一:JSON形式与语法

    1.1:JSON对象

    我们先来看以下数据:

    {

    “ID”: “1001”,

    “name”: “张三”,

    “age”: “24”

    }

    第一个数据就是一个Json对象,观察它的数据形式,可以得出以下语法:

    1:数据在花括号中

    2:数据以键:值对的形式出现(其中键多以字符串形式出现,值可取字符串,数值,甚至其他json对象)

    3:每两个键:值对逗号分隔最后一个键:值对省略逗号

    遵守上面3点,便可以形成一个json对象。

    1.2:JSON对象数组

    接下来我们再看第二个数据,观察它的数据形式,可以得出以下语法:

    [

    {"ID": 1001, "name": "张三", "age": 24},

    {"ID": 1002, "name": "李四", "age": 25},

    {"ID": 1003, "name": "王五", "age": 22}

    ]

    1:数据在方括号中可理解为数组

    2方括号中每个数据json对象形式出现

    3:每两个数据以逗号分隔(最后一个无需逗号)

    遵守上面3点,便可形成一个json对象数组(及一个数组中存储多个json对象

    理解了上面两种基本的形式,我们就可以得出其他的数据形式,例如下面这个:

    {

    "部门名称":"研发部",

    "部门成员":[

    {"ID": 1001, "name": "张三", "age": 24},

    {"ID": 1002, "name": "李四", "age": 25},

    {"ID": 1003, "name": "王五", "age": 22}],

    "部门位置":"xx21"

    }

    这是上面两个基本形式结合出来的一种变形,通过这种变形,使得数据的封装具有很大的灵活性,能让开发者自由的发挥想象力。

    总结:json可以简单的分为基本形式:

    1.json对象2.json对象数组

    两种基本格式组合变形出其他的形式,但其本质还是json对象或者json对象数组中的一种json对象对象数组可以转化为json字符串,使用于不同的场合。

    FastJson的介绍

    JSON协议使用方便,越来越流行,JSON的处理器很多,这里我介绍一下FastJson,FastJson是阿里的开源框架,被不少企业使用,是一个极其优秀的Json框架,Github地址: FastJson

    1.FastJson的特点

    1.FastJson数度快,无论序列化和反序列化,都是当之无愧的fast

    2.功能强大(支持普通JDK类包括任意Java Bean ClassCollectionMapDateenum)

    3.零依赖(没有依赖其它任何类库)

    2.Fastjson中的经常调用的方法

    parse(String text); // JSON文本parseJSONObject或者JSONArray 

    parseObject(String text)// JSON文本parseJSONObject 

    parseArray(String text); // JSON文本parseJSONArray

    toJSONString(Object object); // JavaBean序列化JSON文本 

    应用:

    Json.java

     1 package cn.sxt;
     2 
     3 import java.io.IOException;
     4 import java.util.ArrayList;
     5 import java.util.HashMap;
     6 
     7 import javax.servlet.ServletException;
     8 import javax.servlet.annotation.WebServlet;
     9 import javax.servlet.http.HttpServlet;
    10 import javax.servlet.http.HttpServletRequest;
    11 import javax.servlet.http.HttpServletResponse;
    12 
    13 import com.alibaba.fastjson.JSON;
    14 
    15 /**
    16  * Servlet implementation class Json
    17  */
    18 @WebServlet("/Json")
    19 public class Json extends HttpServlet {
    20     private static final long serialVersionUID = 1L;
    21        
    22     /**
    23      * @see HttpServlet#HttpServlet()
    24      */
    25     public Json() {
    26         super();
    27         // TODO Auto-generated constructor stub
    28     }
    29 
    30     /**
    31      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    32      */
    33     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    34         // TODO Auto-generated method stub
    35         //response.getWriter().append("Served at: ").append(request.getContextPath());
    36         request.setCharacterEncoding("UTF-8");
    37         response.setCharacterEncoding("UTF-8");
    38         response.setContentType("text/json");
    39         
    40         //json数据提交给前端
    41         HashMap<String,Object> hashMap = new HashMap<String,Object>();
    42         hashMap.put("name", "蔡徐坤");
    43         hashMap.put("age", "21");
    44         hashMap.put("height", "183cm");
    45         
    46         ArrayList<String> likeList = new ArrayList<String>();
    47         likeList.add("唱");
    48         likeList.add("跳");
    49         likeList.add("rap");
    50         likeList.add("打篮球");
    51         
    52         hashMap.put("like", likeList);
    53         //将java对象转化为json字符串
    54         String jsonString = JSON.toJSONString(hashMap);
    55         response.getWriter().println(jsonString);
    56         
    57     }
    58 
    59     /**
    60      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    61      */
    62     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    63         // TODO Auto-generated method stub
    64         doGet(request, response);
    65     }
    66 
    67 }

    Index.html

     1 <!DOCTYPE html>
     2 <html>
     3 <head>
     4 <meta charset="UTF-8">
     5 <title>Insert title here</title>
     6 <script src="js/jquery-1.11.0.js"></script>
     7 </head>
     8 <body>
     9 
    10 <script>
    11     $.get('./Json').then(function(res){
    12         console.log(res)
    13         
    14         $("body").append(`
    15                 <h1>${res.name}</h1>
    16                 <h2>${res.height}</h2>
    17                 <h3>${res.age}</h3>
    18         `)
    19         
    20         for(var i=0;i<res.like.length;i++){
    21             $("body").append(`<h3>${i+1}:${res.like[i]}</h3>`)
    22         }
    23     })
    24     
    25     var data = {
    26             json:`
    27             {
    28             "partname":"研发部",
    29             "partman":[
    30             {"ID": 1001, "name": "张三", "age": 24},
    31             {"ID": 1002, "name": "李四", "age": 25},
    32             {"ID": 1003, "name": "王五", "age": 22}],
    33             "position":"xx楼21号"
    34             }`
    35         }
    36     /* $.ajax({
    37         url:"./SetJson",
    38         data:data,
    39         method:"POST",//post提交表单数据
    40         complete:function(res){
    41             console.log(res)
    42         }
    43     }) */
    44     $.ajax({
    45         url:"./SetJson",
    46         data:data,
    47         method:"POST",//post提交表单数据
    48         complete:function(res){
    49             console.log(res)
    50         }
    51     })
    52     
    53 
    54     
    55     
    56 </script>
    57 </body>
    58 </html>

    SetJson.java

     1 package cn.sxt;
     2 
     3 import java.io.IOException;
     4 import javax.servlet.ServletException;
     5 import javax.servlet.annotation.WebServlet;
     6 import javax.servlet.http.HttpServlet;
     7 import javax.servlet.http.HttpServletRequest;
     8 import javax.servlet.http.HttpServletResponse;
     9 
    10 import com.alibaba.fastjson.JSON;
    11 import com.alibaba.fastjson.JSONArray;
    12 import com.alibaba.fastjson.JSONObject;
    13 
    14 /**
    15  * Servlet implementation class SetJson
    16  */
    17 @WebServlet("/SetJson")
    18 public class SetJson extends HttpServlet {
    19     private static final long serialVersionUID = 1L;
    20        
    21     /**
    22      * @see HttpServlet#HttpServlet()
    23      */
    24     public SetJson() {
    25         super();
    26         // TODO Auto-generated constructor stub
    27     }
    28 
    29     /**
    30      * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
    31      */
    32     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    33         // TODO Auto-generated method stub
    34         response.getWriter().append("Served at: ").append(request.getContextPath());
    35     }
    36 
    37     /**
    38      * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
    39      */
    40     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    41         // TODO Auto-generated method stub
    42         //doGet(request, response);
    43         request.setCharacterEncoding("UTF-8");
    44         response.setCharacterEncoding("UTF-8");
    45         response.setContentType("text/json");
    46         response.getWriter().print("成功获取:"+request.getParameter("json"));
    47         
    48         String jsonStr = request.getParameter("json");
    49         JSONObject parseObject = JSON.parseObject(jsonStr);//json数据转换为json对象
    50         System.out.println(parseObject.get("partname"));
    51         System.out.println(parseObject.get("position"));
    52         System.out.println(parseObject.get("partman"));
    53         Object partman = parseObject.get("partman");
    54         System.out.println(partman);
    55         JSONArray parseArray = JSON.parseArray(partman.toString());//json数据解析为json数组
    56         System.out.println(parseArray.get(2));
    57         
    58         
    59     }
    60 
    61 }
  • 相关阅读:
    Typora集成免费图床:PicGo + Gitee
    Github shields徽章配置方法介绍
    Python爬虫的简易流程
    MVC学习系列——Filter扩展
    MVC学习系列——ActionResult扩展
    JQuery插件,傻傻分不清!
    闲谈前端编码解码、C#编码解码。
    年终总结和职业规划
    MVC学习系列——记一次失败面试后,感想。
    C/C++四种退出线程的方法
  • 原文地址:https://www.cnblogs.com/qq308015824/p/11033030.html
Copyright © 2011-2022 走看看