美文网首页Python
json语法和json解析

json语法和json解析

作者: 测试老杨 | 来源:发表于2019-05-15 16:48 被阅读42次

    json介绍

    json是一种数据结构,任何东西都可以使用json格式的数据来表示。


    image.png

    json格式的天气预报数据如下:

    {
      "time": "2019-05-16 11:17:51",
      "cityInfo": {
        "city": "上海市",
        "cityId": "101020100",
        "parent": "上海",
        "updateTime": "10:48"
      },
      "date": "20190516",
      "message": "Success !",
      "status": 200,
      "data": {
        "shidu": "93%",
        "pm25": 41,
        "pm10": 42,
        "quality": "良",
        "wendu": "19",
        "ganmao": "极少数敏感人群应减少户外活动",
        "yesterday": {
          "date": "15",
          "sunrise": "05:00",
          "high": "高温 22.0℃",
          "low": "低温 18.0℃",
          "sunset": "18:42",
          "aqi": 35,
          "ymd": "2019-05-15",
          "week": "星期三",
          "fx": "东南风",
          "fl": "<3级",
          "type": "小雨",
          "notice": "雨虽小,注意保暖别感冒"
        },
        "forecast": [
          {
            "date": "16",
            "sunrise": "04:59",
            "high": "高温 24.0℃",
            "low": "低温 19.0℃",
            "sunset": "18:43",
            "aqi": 50,
            "ymd": "2019-05-16",
            "week": "星期四",
            "fx": "东风",
            "fl": "3-4级",
            "type": "小雨",
            "notice": "雨虽小,注意保暖别感冒"
          },
          {
            "date": "17",
            "sunrise": "04:58",
            "high": "高温 26.0℃",
            "low": "低温 20.0℃",
            "sunset": "18:43",
            "aqi": 48,
            "ymd": "2019-05-17",
            "week": "星期五",
            "fx": "东南风",
            "fl": "3-4级",
            "type": "小雨",
            "notice": "雨虽小,注意保暖别感冒"
          },
          {
            "date": "18",
            "sunrise": "04:58",
            "high": "高温 27.0℃",
            "low": "低温 18.0℃",
            "sunset": "18:44",
            "aqi": 72,
            "ymd": "2019-05-18",
            "week": "星期六",
            "fx": "西北风",
            "fl": "3-4级",
            "type": "多云",
            "notice": "阴晴之间,谨防紫外线侵扰"
          },
          {
            "date": "19",
            "sunrise": "04:57",
            "high": "高温 26.0℃",
            "low": "低温 18.0℃",
            "sunset": "18:45",
            "aqi": 62,
            "ymd": "2019-05-19",
            "week": "星期日",
            "fx": "南风",
            "fl": "<3级",
            "type": "小雨",
            "notice": "雨虽小,注意保暖别感冒"
          },
          {
            "date": "20",
            "sunrise": "04:57",
            "high": "高温 25.0℃",
            "low": "低温 17.0℃",
            "sunset": "18:45",
            "aqi": 44,
            "ymd": "2019-05-20",
            "week": "星期一",
            "fx": "北风",
            "fl": "4-5级",
            "type": "多云",
            "notice": "阴晴之间,谨防紫外线侵扰"
          },
          {
            "date": "21",
            "sunrise": "04:56",
            "high": "高温 26.0℃",
            "low": "低温 18.0℃",
            "sunset": "18:46",
            "aqi": 58,
            "ymd": "2019-05-21",
            "week": "星期二",
            "fx": "南风",
            "fl": "<3级",
            "type": "晴",
            "notice": "愿你拥有比阳光明媚的心情"
          },
          {
            "date": "22",
            "sunrise": "04:55",
            "high": "高温 28.0℃",
            "low": "低温 17.0℃",
            "sunset": "18:47",
            "ymd": "2019-05-22",
            "week": "星期三",
            "fx": "南风",
            "fl": "<3级",
            "type": "多云",
            "notice": "阴晴之间,谨防紫外线侵扰"
          }
        ]
      }
    }
    

    json语法

    1、表示对象的话,使用{开始,使用}结束,比如:

    {"empno":1001,"ename":"张三","isMale":true,"hiredate":1557978889881}
    

    2、表示数组的话,使用[开始,使用]结束,比如:

    [{"empno":1001,"ename":"张三","isMale":true},{"empno":1002,"ename":"李四"}]
    

    3、特殊字符的含义
    1)[ 表示数组的开始
    2)] 表示数组的结束
    3){ 表示对象的开始
    4)} 表示对象的结束
    5)" 定义属性名,以及用来表示字符串类型的数据
    6): 连接属性名和属性值
    7), 分隔符(属性之间使用该符号分隔,元素之间使用该符号分隔)
    4、怎么判断是对象还是数组
    1)如果json串是以 { 开始,以 } 结束的话,则表示对象
    2)如果json串是以 [ 开始,以 ] 结束的话,则表示数组
    5、json支持嵌套
    1)对象里面可以嵌套对象,比如:

    {"empno":1003,"ename":"王五","dept":{"dno":10,"dname":"研发","loc":"上海"}}
    

    2)数组里面可以嵌套对象,比如:

    [{"empno":1001,"ename":"张三","isMale":true},{"empno":1002,"ename":"李四"}]
    

    3)对象里面可以嵌套数组

    {"code":200,"data":[{"empno":1001,"ename":"张三"},{"empno":1002,"ename":"李四"}]}
    

    fastjson介绍

    1、什么是fastjson?
    fastjson是阿里巴巴的开源JSON解析库,它可以解析JSON格式的字符串,支持将Java Bean序列化为JSON字符串,也可以从JSON字符串反序列化到JavaBean。
    2、fastjson的优点
    1)速度快
    fastjson相对其他JSON库的特点是快,从2011年fastjson发布1.1.x版本之后,其性能从未被其他Java实现的JSON库超越。
    2)使用广泛
    fastjson在阿里巴巴大规模使用,在数万台服务器上部署,fastjson在业界被广泛接受。在2012年被开源中国评选为最受欢迎的国产开源软件之一。
    3)测试完备
    fastjson有非常多的testcase,在1.2.11版本中,testcase超过3321个。每次发布都会进行回归测试,保证质量稳定。
    4)使用简单
    fastjson的API十分简洁。

    String text = JSON.toJSONString(obj); //序列化
    VO vo = JSON.parseObject("{...}", VO.class); //反序列化
    

    5)功能完备
    支持泛型,支持流处理超大文本,支持枚举,支持序列化和反序列化扩展。

    将json格式的字符串转成json数组(json对象的数组)

    json串内容的格式如下:

    [
      {
        "_id": 1,
        "id": 1,
        "pid": 0,
        "city_code": "101010100",
        "city_name": "北京"
      },
      {
        "_id": 2,
        "id": 2,
        "pid": 0,
        "city_code": "",
        "city_name": "安徽"
      },
      {
        "_id": 3,
        "id": 3,
        "pid": 0,
        "city_code": "",
        "city_name": "福建"
      },
      {
        "_id": 4,
        "id": 4,
        "pid": 0,
        "city_code": "",
        "city_name": "甘肃"
      },
      {
        "_id": 5,
        "id": 5,
        "pid": 0,
        "city_code": "",
        "city_name": "广东"
      },
      {
        "_id": 7,
        "id": 7,
        "pid": 0,
        "city_code": "",
        "city_name": "贵州"
      },
      {
        "_id": 15,
        "id": 15,
        "pid": 0,
        "city_code": "",
        "city_name": "江苏"
      },
      {
        "_id": 24,
        "id": 24,
        "pid": 0,
        "city_code": "101020100",
        "city_name": "上海"
      },
      {
        "_id": 25,
        "id": 25,
        "pid": 0,
        "city_code": "",
        "city_name": "四川"
      },
      {
        "_id": 26,
        "id": 26,
        "pid": 0,
        "city_code": "101030100",
        "city_name": "天津"
      }
    ]
    

    代码如下:

    package day03;
    
    import org.apache.http.HttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.util.EntityUtils;
    
    import com.alibaba.fastjson.*;
    
    public class CityJsonTest {
    
        public static void main(String[] args) throws Exception{
            // 创建一个可关闭的客户端工具
            CloseableHttpClient client = HttpClients.createDefault();
            // 创建一个GET请求
            HttpGet request = new HttpGet("http://cdn.sojson.com/_city.json");
            // 发送该请求
            HttpResponse response = client.execute(request);
            // 将响应正文(body)转换字符串
            String data = EntityUtils.toString(response.getEntity());
            // 将data解析为JSON数组
            JSONArray cities = JSON.parseArray(data);
            //
            for(Object city:cities){
                JSONObject obj = (JSONObject)city;
                //
                if(obj.get("city_name").equals("上海")){
                    System.out.println(obj.get("city_code"));//101020100
                    break;
                }
            }
            client.close();//关闭给客户端
        }
    
    }
    

    将json格式的字符串转成json对象

    天气预报json数据的解析思路:
    1)将整个json串解析为JSON对象

    JSONObject obj= JSON.parseObject(str2);
    

    2)通过属性名获取属性的内容

    JSONObject data = obj.getJSONObject("data");
    

    3)如果解析出来的内容是对象的话,可进一步通过属性名获取里面的内容

    JSONArray forecast = data.getJSONArray("forecast"); 
    

    4)如果解析出来的内容是数组的话,可进一步通过下标获取里面的内容

    JSONObject tomorrow = (JSONObject)forecast.get(1);
    

    代码如下:

    package day03;
    
    import org.apache.http.HttpResponse;
    import org.apache.http.client.methods.HttpGet;
    import org.apache.http.impl.client.CloseableHttpClient;
    import org.apache.http.impl.client.HttpClients;
    import org.apache.http.util.EntityUtils;
    
    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.JSONArray;
    import com.alibaba.fastjson.JSONObject;
    
    public class WeatherJsonTest {
    
        public static void main(String[] args) throws Exception {
            //
            String cityCode = null;
            // 创建一个可关闭的客户端工具
            CloseableHttpClient client = HttpClients.createDefault();
            // 创建一个GET请求
            HttpGet request = new HttpGet("http://cdn.sojson.com/_city.json");
            // 发送该请求
            HttpResponse response = client.execute(request);
            // 将响应正文(body)转换字符串
            String str = EntityUtils.toString(response.getEntity());
            // 将str解析为JSON数组
            JSONArray cities = JSON.parseArray(str);
            //
            for(Object city:cities){
                JSONObject obj = (JSONObject)city;
                //
                if(obj.get("city_name").equals("上海")){
                    //System.out.println(obj.get("city_code"));//101020100
                    cityCode = obj.getString("city_code");
                    break;
                }
            }
            //创建一个请求天气的Get请求
            HttpGet request2 = new HttpGet("http://t.weather.sojson.com/api/weather/city/"+cityCode);
            //发送该请求
            HttpResponse response2 = client.execute(request2);
            // 将响应正文(body)转换字符串
            String str2 = EntityUtils.toString(response2.getEntity());
            //将str2解析为JSON对象
            JSONObject obj= JSON.parseObject(str2);
            //获取data属性的内容
            JSONObject data = obj.getJSONObject("data");
            //获取forecast属性的内容
            JSONArray forecast = data.getJSONArray("forecast");
            //获取明天的天气
            JSONObject tomorrow = (JSONObject)forecast.get(1);
            System.out.println(tomorrow.get("type"));//小雨
            System.out.println(tomorrow.getString("high"));//高温 26.0℃
            System.out.println(tomorrow.getString("low"));//低温 20.0℃        
            client.close();//关闭给客户端
        }
    
    }
    

    JSON字符串解析的小结

    1)将表示对象的json串解析为对象使用parseObject(str)
    2)将表示数组的json串解析为数组使用parseArray(str)
    3)属性的值是对象的话,就使用getJSONObject获取属性的内容
    4)属性的值是数组的话,就使用getJSONArray获取该属性的内容
    5)属性的值是字符串的话,就使用get或者getString获取该属性的内容
    6)属性的值是数值的话,就使用get获取该属性的内容
    7)属性的值是布尔值的话,就使用get获取该属性的内容

    将对象转成json格式的字符串

    代码如下:

    package day03;
    
    import java.util.Date;
    
    import com.alibaba.fastjson.JSON;
    import com.testin.model.Dept;
    import com.testin.model.Employee;
    
    public class ObjectToJSONTest {
        public static void main(String[] args) {
            Dept dept = new Dept(10,"研发","上海");
            Employee emp = new Employee(1001,"张三",true,new Date(),dept);
            //将部门对象转成json格式的字符串
            System.out.println(JSON.toJSONString(dept));
            //
            System.out.println(JSON.toJSONString(emp));
        }
    }
    

    运行结果如下:

    {"dname":"研发","dno":10,"loc":"上海"}
    {"dept":{"dname":"研发","dno":10,"loc":"上海"},"empno":1001,"ename":"张三","hiredate":1557978889881,"male":true}
    

    员工模板的代码如下:

    package com.testin.model;
    
    import java.util.Date;
    
    public class Employee {
        private int empno;
        private String ename;
        private boolean isMale;
        private Date hiredate;
        private Dept dept;
        
        public Employee(int empno, String ename, boolean isMale, Date hiredate, Dept dept) {
            super();
            this.empno = empno;
            this.ename = ename;
            this.isMale = isMale;
            this.hiredate = hiredate;
            this.dept = dept;
        }
    
        public int getEmpno() {
            return empno;
        }
    
        public void setEmpno(int empno) {
            this.empno = empno;
        }
    
        public String getEname() {
            return ename;
        }
    
        public void setEname(String ename) {
            this.ename = ename;
        }
    
        public boolean isMale() {
            return isMale;
        }
    
        public void setMale(boolean isMale) {
            this.isMale = isMale;
        }
    
        public Date getHiredate() {
            return hiredate;
        }
    
        public void setHiredate(Date hiredate) {
            this.hiredate = hiredate;
        }
    
        public Dept getDept() {
            return dept;
        }
    
        public void setDept(Dept dept) {
            this.dept = dept;
        }   
        
    }
    

    部门模板的代码如下:

    package com.testin.model;
    
    public class Dept {
        private int dno;
        private String dname;
        private String loc;
        
        public Dept(int dno, String dname, String loc) {
            super();
            this.dno = dno;
            this.dname = dname;
            this.loc = loc;
        }
    
        public int getDno() {
            return dno;
        }
    
        public void setDno(int dno) {
            this.dno = dno;
        }
    
        public String getDname() {
            return dname;
        }
    
        public void setDname(String dname) {
            this.dname = dname;
        }
    
        public String getLoc() {
            return loc;
        }
    
        public void setLoc(String loc) {
            this.loc = loc;
        }
        
    }
    

    将对象集合转成json格式的字符串

    代码如下:

    package day03;
    
    import java.util.ArrayList;
    import java.util.List;
    
    import com.alibaba.fastjson.JSON;
    import com.testin.model.Dept;
    
    public class ListToJSONTest {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            List<Dept> depts = new ArrayList<Dept>();
            Dept d1 = new Dept(10,"研发","上海");
            Dept d2 = new Dept(20,"销售","上海");
            depts.add(d1);
            depts.add(d2);
            System.out.println(JSON.toJSONString(depts));
        }
    
    }
    

    运行结果如下:

    [{"dname":"研发","dno":10,"loc":"上海"},{"dname":"销售","dno":20,"loc":"上海"}]
    

    参考资料

    [1] json语法
    https://www.runoob.com/json/json-syntax.html
    [2] JSON最佳实践
    http://kimmking.github.io/2017/06/06/json-best-practice/
    [3] fastjson教程
    https://www.w3cschool.cn/fastjson
    [4] Json详解以及fastjson使用教程
    https://blog.csdn.net/srj1095530512/article/details/82529759
    [5] fastjson新手指南
    https://github.com/alibaba/fastjson/wiki/Quick-Start-CN
    [6] 天气预报接口API文档
    https://www.juhe.cn/docs/api/id/73
    [7] 免费天气API,天气JSON API,不限次数获取十五天的天气预报
    https://www.sojson.com/blog/305.html

    微信扫一扫关注该公众号【测试开发者部落】

    image.png
    点击链接加入群聊【软件测试学习交流群】
    https://jq.qq.com/?_wv=1027&k=5eVEhfN
    软件测试学习交流QQ群号:511619105

    相关文章

      网友评论

        本文标题:json语法和json解析

        本文链接:https://www.haomeiwen.com/subject/xgqmaqtx.html