FastJson 介紹


Json詳解

Json是一種輕量級的數據交換格式,采用一種“鍵:值”對的文本格式來存儲和表示數據,在系統交換數據過程中常常被使用,是一種理想的數據交換語言。在使用 Java 做 Web 開發時,不可避免的會遇到 Json 的使用。

JSON形式與語法

我們先來看以下數據:

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

觀察它的數據形式,可以得出以下語法:

  1. 數據在花括號中
  2. 數據以鍵:值對的形式出現(其中鍵多以字符串形式出現,值可取字符串,數值,甚至其他 json 對象)
  3. 每兩個鍵:值對以逗號分隔(最后一個鍵:值對省略逗號)
遵守上面3點,便可以形成一個json對象。

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}], "部門位置":"xx樓21號" }

這是上面兩個基本形式結合出來的一種變形,通過這種變形,使得數據的封裝具有很大的靈活性,能讓開發者自由的發揮想象力。

總結:json 可以簡單的分為基本形式:json 對象,json 對象數組。兩種基本格式組合變形出其他的形式,但其本質還是 json 對象或者 json 對象數組中的一種。json 對象或對象數組可以轉化為 json 字符串,使用於不同的場合。

FastJson

介紹

JSON 協議使用方便,越來越流行,JSON 的處理器有很多,這里我介紹一下FastJson,FastJson 是阿里的開源框架,被不少企業使用,是一個極其優秀的 Json 框架,Github 地址: FastJson。

FastJson的特點

  1. FastJson數度快,無論序列化和反序列化,都是當之無愧的fast
  2. 功能強大(支持普通JDK類包括任意Java Bean Class、Collection、Map、Date或enum)
  3. 零依賴(沒有依賴其它任何類庫)

Fastjson中的經常調用的方法

  • parse(String text);: 把JSON文本parse為JSONObject或者JSONArray
  • parseObject(String text);: 把JSON文本parse成JSONObject
  • parseArray(String text);: 把JSON文本parse成JSONArray
  • toJSONString(Object object);: 將JavaBean序列化為JSON文本

實例

服務器接收請求數據,發送 JSON 回瀏覽器,並根據不同的請求方式,分別解決中文亂碼問題:

 1 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 2         request.setCharacterEncoding("utf-8");
 3         response.setCharacterEncoding("utf-8");
 4         response.setContentType("text/json;charset=utf-8");
 5         //允許所有IP地址和端口請求
 6         response.setHeader("Access-Control-Allow-Origin", "*"); 
 7         //允許所有的文檔類型請求 
 8         response.setHeader("Access-Control-Content-Type", "*"); 
 9         HashMap<String, String> map = new HashMap<String, String>();
10         map.put("user", new String(request.getParameter("user").getBytes("ISO-8859-1"),"utf-8"));
11         map.put("psw", new String(request.getParameter("psw").getBytes("ISO-8859-1"),"utf-8"));
12         System.out.println(new String(request.getParameter("user").getBytes("ISO-8859-1"),"utf-8"));
13         String jsonString = JSON.toJSONString(map);
14         response.getWriter().println(jsonString);
15     }
16 
17     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("utf-8");
18         request.setCharacterEncoding("utf-8");
19         response.setCharacterEncoding("utf-8");
20         response.setContentType("text/json;charset=utf-8");
21         //允許所有IP地址和端口請求
22         response.setHeader("Access-Control-Allow-Origin", "*"); 
23         //允許所有的文檔類型請求 
24         response.setHeader("Access-Control-Content-Type", "*"); 
25         HashMap<String, String> map = new HashMap<String, String>();
26         map.put("user", request.getParameter("user"));
27         map.put("psw", request.getParameter("psw"));
28         System.out.println(request.getParameter("user"));
29         String jsonString = JSON.toJSONString(map);
30         response.getWriter().println(jsonString);
31     }

服務器接收 JSON 並取出數據發回瀏覽器:

瀏覽器:

 1 $.ajax({
 2     url: 'http://localhost:8080/RequestNResponse/GetJSON',
 3     method: 'GET',
 4     data: {
 5         json:
 6         `{
 7             "username": "張三",
 8             "age": 23,
 9             "hobby":["籃球","足球","羽毛球"]
10         }`
11     },
12     complete: function (res) {
13         console.log(res)
14         $('body').append(`<h1>${res.responseText}</h1>`)
15     }
16 })

服務器:

 1 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 2         request.setCharacterEncoding("utf-8");
 3         response.setCharacterEncoding("utf-8");
 4         response.setContentType("text/html;charset=utf-8");
 5         //允許所有IP地址和端口請求
 6         response.setHeader("Access-Control-Allow-Origin", "*"); 
 7         //允許所有的文檔類型請求 
 8         response.setHeader("Access-Control-Content-Type", "*"); 
 9         String jsonStr = new String(request.getParameter("json").getBytes("ISO-8859-1"), "utf-8");
10         JSONObject object = JSON.parseObject(jsonStr);
11         response.getWriter().println("username:" + object.get("username"));
12         response.getWriter().println("username:" + object.get("age"));
13         JSONArray hobbies = (JSONArray) object.get("hobby");
14         hobbies.forEach(obj -> {
15             try {
16                 response.getWriter().println(obj);
17             } catch (IOException e) {
18                 // TODO Auto-generated catch block
19                 e.printStackTrace();
20             }
21         });
22     }
23 
24     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
25         request.setCharacterEncoding("utf-8");
26         response.setCharacterEncoding("utf-8");
27         response.setContentType("text/html;charset=utf-8");
28         //允許所有IP地址和端口請求
29         response.setHeader("Access-Control-Allow-Origin", "*"); 
30         //允許所有的文檔類型請求 
31         response.setHeader("Access-Control-Content-Type", "*"); 
32         String jsonStr = request.getParameter("json");
33         JSONObject object = JSON.parseObject(jsonStr);
34         response.getWriter().println("username:" + object.get("username"));
35         response.getWriter().println("username:" + object.get("age"));
36         JSONArray hobbies = (JSONArray) object.get("hobby");
37         hobbies.forEach(obj -> {
38             try {
39                 response.getWriter().println(obj);
40             } catch (IOException e) {
41                 // TODO Auto-generated catch block
42                 e.printStackTrace();
43             }
44         });
45     }


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM