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     }

转载于:https://www.cnblogs.com/carlosouyang/p/11117148.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值