JSON解析
目录
一、 JSON简介
二、 JSON语法
三、 JSON的用途
四、Java解析JSON
五、使用Fastjson
一、 JSON简介
JSON
是一种轻量级的数据交换格式。它基于 ECMAScript
(European Computer Manufacturers Association
, 欧洲计算机协会制定的JavaScript
规范)的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON
成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。
二、 JSON语法
1、使用大括号 { } 保存对象,每个对象由若干数据组成
2、每个数据由key:value
键值对组成
3、数据之间使用逗号 , 分隔
4、使用 \ 进行特殊字符的转义
5、使用中括号 [ ] 保存数组(集合),数组(集合)可以包含多个对象
三、 JSON的用途
JSON
做为一种轻量级的数据格式,它的用途主要是在计算机系统之间进行数据的传递。JSON作为数据传输的格式,有几个显著的优点:
1、JSON
只允许使用UTF-8
编码,不存在编码问题;
2、JSON
内容仅包含key-value
键值对,格式简单,不存在冗余结构,是一种轻量级结构;
3、浏览器内置JSON
支持,如果把数据用JSON
发送给浏览器,可以用JavaScript
直接处理;
所以,开发Web
应用的时候,使用JSON
作为数据传输,在浏览器端非常方便。因为JSON
天生适合JavaScript
处理,所以,绝大多数REST API
都选择JSON
作为数据传输格式。
四、Java解析JSON
在使用Java
进行应用程序的开发中,我们会面临类似“将Java对象转换成JSON
格式”或者“将JSON
格式的数据转换成Java
对象“的需求,所以我们需要掌握如何使用第三方库来进行JSON格式数据的解析。
常用的用于解析JSON
的第三方库有:
Jackson
Gson
Fastjson
五、使用Fastjson
fastjson
是阿里巴巴的开源JSON
解析库,它可以解析 JSON
格式的字符串,支持将 Java Bean
序列化为 JSON
字符串,也可以从 JSON
字符串反序列化到 JavaBean
1、 Fastjson 的优点:速度快、使用广泛、测试完备、使用简单、功能完备
2、Fastjson的主要对象:
(1)JSON
接口:提供json
解析操作的入口方法,用于原始转换。
(2)JSONObject
类 : 封装json
格式的对象。
(3)JSONArray
类: 封装json
格式的集合。
3、 JSON接口
JSON
接口的作用主要是用于原始转换:将Java
对象序列化为JSON
字符串 或 将JSON
字符串反序列化为Java
对象。常用方法有三个,分别是:
(1)JSON.toJSONString(Object object):将Java对象 "序列化"(转换) 为JSON字符串
// 实体数据
Weather weather = new Weather();
weather.setCity("西安");
weather.setComfort_index("非常舒适");
weather.setDate_y("2022年07月10日");// 转换为json格式的字符串
String json = JSON.toJSONString(weather);
System.out.println(json);
(2)JSON.parseObject(String text):将JSON字符串反序列化为Java对象
String jsonString ="{\"city\":\"西安\",\"temperature\":\"42\",\"weather\":\"炎热\",\"wind\":\"微微风\"}";//1、将JSON格式的字符串转换为JSON格式的对象JSONObject jsonObject = JSON.parseObject(jsonString);System.out.println(jsonObject.get("city"));System.out.println(jsonObject.get("temperature"));System.out.println(jsonObject.get("weather"));System.out.println(jsonObject.get("wind"));System.out.println("================");//2、将JSON格式的字符串转换为JavaBean对象//参数一,序列化成JSON格式的字符串,参数二、指定的JavaBean对象类型Weather w1 = JSON.parseObject(jsonString, Weather.class);System.out.println(w1.getCity());System.out.println(w1.toString());//3、第二种方式转成JavaBeanSystem.out.println(w1.toString());Weather w2 = JSON.parseObject(jsonString,new TypeReference<Weather>(){});System.out.println(w2.toString());
(3)JSON.parseArray(String text):将JSON字符串反序列化为JSONArray集合数组
package com.yuan.jsonclass;import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;import java.util.Collection;
import java.util.Iterator;
import java.util.Map;public class Demo06 {public static void main(String[] args) {String jsonString = "{\"城市1\":{\"city\":\"西安\",\"temperature\":\"42\",\"weather\":\"炎热\",\"wind\":\"微微风\"},\"城市2\":{\"city\":\"西安\",\"temperature\":\"42\",\"weather\":\"炎热\",\"wind\":\"微微风\"}}";//将JSON格式字符串转JSON格式对象JSONObject jsonObject = JSON.parseObject(jsonString);//getJSONObject()返回值为JSON格式对象JSONObject jsonObject1 = jsonObject.getJSONObject("城市一");System.out.println(jsonObject1.get("city"));JSONObject jsonObject2 = jsonObject.getJSONObject("城市二");System.out.println(jsonObject2.get("city"));//getObject()Weather w1 = jsonObject.getObject("城市一", Weather.class);System.out.println("城市一的名称为" + w1.getCity());Weather w2 = jsonObject.getObject("城市二", Weather.class);System.out.println("城市二的名称为" + w2.getCity());System.out.println("=====================");Map<String, Weather> map = JSON.parseObject(jsonString, new TypeReference<Map<String, Weather>>() {});//获取所有的值进行遍历Collection<Weather> weathers = map.values();Iterator<Weather> itor = weathers.iterator();while (itor.hasNext()) {System.out.println(itor.next().getCity());}}
}
4、JSONObject类: 底层 LinkedHashMap<String, Object>
JSON
对象JSONObject
中的数据都是以key-value
形式出现,常用的方法:
(1)Object get(String key):获取键对应的值。
(2)getJSONObject(String key):获取该键对应的一个JSONObject对象返回值为JSONObject
(3)getJSONArray(String key):获取该键对应的一个JSONArray对象返回值为JSONArray
5、 JSONArray类:底层 ArrayList<Object>
JSONArray
则是JSON
数组,JSON
数组对象中存储的是若干个JSONObject
对象,所以类中的方法主要用于直接操作JSONObject
对象,常用的方法:
(1)getJSONArray(int index):获取index下标位置对应的value,返回值JSONArray
(2)getJSONObject(int index):获取index下标位置对应的value,返回值JSONObject
package com.yuan.jsonclass;/*** @author 张老师* @version 1.0* @since 2025/7/29*/public class Weather {private String temperature; // 温度private String weather; // 天气private String wind; // 风力private String week; // 星期private String city; // 城市private String date_y; // 日期private String dressing_index; // 穿衣指数private String dressing_advice; // 穿衣建议private String uv_index; // 紫外线指数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;}@Overridepublic String toString() {return "Weather{" +"temperature='" + temperature + '\'' +", wind='" + wind + '\'' +", city='" + city + '\'' +", weather='" + weather + '\'' +'}';}
}
package com.yuan.jsonclass;import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;import java.util.List;public class Demo05 {public static void main(String[] args) {String jsonString="[{\"city\":\"西安\",\"temperature\":\"42\",\"weather\":\"炎热\",\"wind\":\"微微风\"},{\"city\":\"锡林郭勒\",\"temperature\":\"22\",\"weather\":\"凉爽\",\"wind\":\"微风\"}]";//方法3:JSONArray jsonArray = JSON.parseArray(jsonString);for (int i = 0; i <jsonArray.size() ; i++) {JSONObject jsonObject = jsonArray.getJSONObject(i);System.out.println(jsonObject.get("city")+"__"+jsonObject.get("temperature"));}System.out.println("=================");//将List集合JSON。parseArray(jsonString,Weather.class)将JSON格式字符串转换成集合类型List<Weather> w1 = JSON.parseArray(jsonString, Weather.class);for (Weather w:w1) {System.out.println(w.getCity()+"__"+w.getWind());}System.out.println("=================");////new TypeReference<List<Weather>>(){}是万能的,可以转成javabean对象,在T处传入泛型类型List<Weather> list= JSON.parseObject(jsonString, new TypeReference<List<Weather>>(){});for (Weather w:list) {System.out.println(w.getTemperature()+"__"+w.getWeather());}}
}
package com.yuan.jsonclass;import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.alibaba.fastjson2.TypeReference;import java.util.Collection;
import java.util.Iterator;
import java.util.Map;public class Demo06 {public static void main(String[] args) {String jsonString = "{\"城市1\":{\"city\":\"西安\",\"temperature\":\"42\",\"weather\":\"炎热\",\"wind\":\"微微风\"},\"城市2\":{\"city\":\"西安\",\"temperature\":\"42\",\"weather\":\"炎热\",\"wind\":\"微微风\"}}";//将JSON格式字符串转JSON格式对象JSONObject jsonObject = JSON.parseObject(jsonString);//getJSONObject()返回值为JSON格式对象JSONObject jsonObject1 = jsonObject.getJSONObject("城市一");System.out.println(jsonObject1.get("city"));JSONObject jsonObject2 = jsonObject.getJSONObject("城市二");System.out.println(jsonObject2.get("city"));//getObject()Weather w1 = jsonObject.getObject("城市一", Weather.class);System.out.println("城市一的名称为" + w1.getCity());Weather w2 = jsonObject.getObject("城市二", Weather.class);System.out.println("城市二的名称为" + w2.getCity());System.out.println("=====================");Map<String, Weather> map = JSON.parseObject(jsonString, new TypeReference<Map<String, Weather>>() {});//获取所有的值进行遍历Collection<Weather> weathers = map.values();Iterator<Weather> itor = weathers.iterator();while (itor.hasNext()) {System.out.println(itor.next().getCity());}}
}