JSON解析

发布于:2024-05-05 ⋅ 阅读:(28) ⋅ 点赞:(0)

JSON简介

        JSON是一种轻量级的数据交换格式,它采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得JSON成为理想的数据交换语言,易于人的阅读和编写,同时也有利于机器解析和生成,并有效地提升网络传输效率。

JSON的具体使用方法

1、JSON的语法格式

注意:

使用大括号{}保存对象。对象由若干条数据组成,每条数据由key:value键值对组成

数据之间使用逗号,分隔

key和value均需要用双引号包围,并且双引号需要用转义字符\进行转义

String message="{\"orderID\":\"10001\",\"payment\":\"23847\"}";

使用中括号[]保存保存数组,数组可以包含若干个对象

String message="[{\"orderID\":\"10001\",\"payment\":\"23847\"}, 
                 {\"orderID\":\"10002\",\"payment\":\"34577\"},
                 {\"orderID\":\"10003\",\"payment\":\"86544\"}]";

JSON的用途

        JSON主要是在计算机系统之间进行数据的传递,但是要注意:JSON只允许使用UTF-8编码。

JSON解析

        在使用Java进行应用程序的开发中,我们会面临:将Java对象转换成JSON格式,或者将JSON格式转换成Java对象的需求,此时我们就需要利用第三方库来进行JSON​​​​​​​解析。常用的用于解析JSON的第三方库有:

①Jackson

②Gson

③Fastjson

...

 Fastjson

        Fastjson是阿里巴巴的开源JSON解析库,它可以解析JSON格式的字符串。Fastjson的主要使用对象是:

JSON接口:提供JSON字符串进行解析的入口操作,进行原始转换

JSONObject类:封装JSON格式的对象

JSONArray类:封装JSON格式的集合

JSON接口

        JSON接口的主要作用是用于:将Java对象序列化为JSON字符串,或者将JSON字符串反序列化为Java对象

将JAVA对象转换为JSON格式字符串

//使用JSON.toJSONString(Object o)方法

首先我们要准备好一个Weather类

import com.alibaba.fastjson2.annotation.JSONField;
	public class Weather {
		private String temperature; // 温度
		private String weather; // 天气
		private String wind; // 风力
		private String week; // 星期
		private String city; // 城市
		
		@JSONField(name = "today")
		private String date_y; // 日期
		
		private String dressing_index; // 穿衣指数
		private String dressing_advice; // 穿衣建议
		private String uv_index; // 紫外线指数
		
		@JSONField(name="comfort")
		private String comfort_index; // 舒适指数
		
		private String wash_index; // 洗衣指数
		private String travel_index; // 旅行指数
		private String exercise_index; // 晨练指数
		private String drying_index; // 晾晒指数

		public void setTemperature(String temperature) {
			this.temperature = temperature;
		}

		public String getTemperature() {
			return temperature;
		}

		public void setWeather(String weather) {
			this.weather = weather;
		}

		public String getWeather() {
			return weather;
		}

		public void setWind(String wind) {
			this.wind = wind;
		}

		public String getWind() {
			return wind;
		}

		public void setWeek(String week) {
			this.week = week;
		}

		public String getWeek() {
			return week;
		}

		public void setCity(String city) {
			this.city = city;
		}

		public String getCity() {
			return city;
		}

		public void setDate_y(String date_y) {
			this.date_y = date_y;
		}

		public String getDate_y() {
			return date_y;
		}

		public void setDressing_index(String dressing_index) {
			this.dressing_index = dressing_index;
		}

		public String getDressing_index() {
			return dressing_index;
		}

		public void setDressing_advice(String dressing_advice) {
			this.dressing_advice = dressing_advice;
		}

		public String getDressing_advice() {
			return dressing_advice;
		}

		public void setUv_index(String uv_index) {
			this.uv_index = uv_index;
		}

		public String getUv_index() {
			return uv_index;
		}

		public void setComfort_index(String comfort_index) {
			this.comfort_index = comfort_index;
		}

		public String getComfort_index() {
			return comfort_index;
		}

		public void setWash_index(String wash_index) {
			this.wash_index = wash_index;
		}

		public String getWash_index() {
			return wash_index;
		}

		public void setTravel_index(String travel_index) {
			this.travel_index = travel_index;
		}

		public String getTravel_index() {
			return travel_index;
		}

		public void setExercise_index(String exercise_index) {
			this.exercise_index = exercise_index;
		}

		public String getExercise_index() {
			return exercise_index;
		}

		public void setDrying_index(String drying_index) {
			this.drying_index = drying_index;
		}

		public String getDrying_index() {
			return drying_index;
		}

	}
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
public class Demo02_WeatherJson {
    public static void main(String[] args) {
        //新建一个Weather对象(java对象)
        Weather weather=new Weather();
        weather.setTemperature("39℃");
		weather.setCity("西安");
		weather.setComfort_index("非常舒适");
		weather.setDate_y("2024年4月28日");

        String jsonStr=JSON.toJSONString(weather);
        System.out.println(jsonStr);
    }
}

输出结果:{"city":"西安","comfort":"非常舒适","temperature":"39℃","today":"2024年4月28日"}

将JSON格式字符串转换为JAVA对象

//使用JSON.parseObject(String s)方法

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

public class Demo02_WeatherJson {
	public static void main(String[] args) {
        //创建一个JSON格式的字符串
        String resultJsonStr="{\"city\":\"西安\",
                               \"comfort\":\"非常舒适\",
                               \"today\":\"2024年4月28日\",
                               \"temperature\":\"39℃\"}" ;
        //将JSON格式的字符串转换为Java对象
        JSONObject jsonObj=JSON.parseObject(resultJsonStr);
        System.out.println(jsonObj);
        System.out.println(jsonObj.getString("comfort"));
        System.out.println(jsonObj.getString("city"));
        System.out.println(jsonObj.getString("today"));

    }
}

输出结果:

{"city":"西安","comfort":"非常舒适","date":"2024年4月28日","temperature":"39℃"}
非常舒适
西安
2024年4月28日

将JSON格式字符串转换为自定义类型的JAVA对象
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;

//JSON接口:提供JSON字符串进行解析的入口操作,进行原始转换
public class Demo02_WeatherJson {
	public static void main(String[] args) {
        String resultJsonStr="{\"city\":\"西安\",
                                \"comfort\":\"非常舒适\",
                                \"today\":\"2024年4月28日\",
                                \"temperature\":\"39℃\"}" ;
        Weather weather=JSON.parseObject(resultJsonStr);
        System.out.println("今日温度:"+weather.getTemperature());
        System.out.println("日期:"+weather.getDate_y());
    }
}

输出结果:

今日温度:39℃
日期:2024年4月28日

JSONObject类

        JSONObject类主要用于封装key:value形式的数据,它继承自LInkedHashMap接口

将JSON格式字符串转换为自定义类型的JAVA对象

//使用JSON.parseObject(String s,Class<T> class)方法

public class Demo03_policeStation {
	public static void main(String[] args) {
        //JSON格式的数据
		String jsonStr= "{ \"name\": \"文保分局沪东高校派出所\",             
                           \"addr\": \"中山北一路801号\", 
                           \"tel\": \"22027732\"}";
        //先将JSON字符串转换为自定义的PoliceStation类型
       PoliceStation policeStation=JSON.parseObject(jsonStr,
                                                 PoliceStation.class);
    	System.out.println("名称:"+policeStation.getName());
		System.out.println("电话:"+policeStation.getTel());
		System.out.println("地址:"+policeStation.getAddr());
    }
}

输出结果:

名称:文保分局沪东高校派出所
电话:22027732
地址:中山北一路801号

JSONArray类

        JSONArray主要用于JSON数组,JSON数组存储的是若干个JSONObject对象。所以类中的方法主要用于直接操作JSONObject数组,JSONArray主要用于封装一个JSON集合,它继承自ArrayList类

import java.util.List;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
public class Demo04_JSONArray {
	public static void main(String[] args) {
		String jsonStr="[{ \"name\": \"文保分局沪东高校派出所\",         
                            \"addr\": \"中山北一路801号\",
                            \"tel\": \"22027732\"}, 
                         {\"name\": \"文保分局沪西高校派出所\",
                            \"addr\": \"芙蓉江路55号\",
                            \"tel\": \"62751704\" },
                         {\"name\": \"水上公安局吴淞水上派出所\", 			                
                            \"addr\": \"淞浦路187号\",
                            \"tel\": \"56671442\" }, 
                        {\"name\": \"水上公安局杨浦水上派出所\", 
                            \"addr\": \"杨树浦路1291号\", 			        
                            \"tel\": \"65898004\"}, 			    
                        {\"name\": \"水上公安局外滩水上派出所\", 			        
                            \"addr\": \"中山东二路8弄3号\",
                            \"tel\": \"63305388\"}, 
                        {\"name\": \"水上公安局石洞口水上派出所\",
                            \"addr\": \"盛石路18号\",
                            \"tel\": \"56152176\"}]";
        JSONArray jsonArray=JSON.parseArray(jsonStr);

        //做法1
		//转换成list
        List<PoliceStation> list=JSON.parseArray(jsonStr, 
                                                PoliceStation.class);
        //遍历list,获取每一个PoliceStation对象
        for(int i=0;i<list.size();i++) {
            PoliceStation policeStation=list.get(i);
            System.out.println("名称:"+policeStation.getName());
			System.out.println("电话:"+policeStation.getTel());
			System.out.println("地址:"+policeStation.getAddr());
        }

        //做法2
		//遍历JSONArray,遍历获取每一个JSONObject对象
		for(int i=0;i<jsonArray.size();i++) {
            JSONObject jsonObj=jasonArray.getJSONObject(i);
            System.out.println("名称:"+jsonObj.get("name"));
			System.out.println("电话:"+jsonObj.get("tel"));
			System.out.println("地址:"+jsonObj.get("addr"));
        }
    }
}

输出结果:

名称:文保分局沪东高校派出所
电话:22027732
地址:中山北一路801号
-----------------------
名称:文保分局沪西高校派出所
电话:62751704
地址:芙蓉江路55号
-----------------------
名称:水上公安局吴淞水上派出所
电话:56671442
地址:淞浦路187号
-----------------------
名称:水上公安局杨浦水上派出所
电话:65898004
地址:杨树浦路1291号
-----------------------
名称:水上公安局外滩水上派出所
电话:63305388
地址:中山东二路8弄3号
-----------------------
名称:水上公安局石洞口水上派出所
电话:56152176
地址:盛石路18号
-----------------------
名称:文保分局沪东高校派出所
电话:22027732
地址:中山北一路801号
名称:文保分局沪西高校派出所
电话:62751704
地址:芙蓉江路55号
名称:水上公安局吴淞水上派出所
电话:56671442
地址:淞浦路187号
名称:水上公安局杨浦水上派出所
电话:65898004
地址:杨树浦路1291号
名称:水上公安局外滩水上派出所
电话:63305388
地址:中山东二路8弄3号
名称:水上公安局石洞口水上派出所
电话:56152176
地址:盛石路18号