JSON解析

ops/2024/10/21 9:08:34/

JSON简介

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

JSON的具体使用方法

1、JSON的语法格式

注意:

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

数据之间使用逗号,分隔

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

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

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

java">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类

java">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;}}
java">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)方法

java">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对象
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)方法

java">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类

java">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//转换成listList<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号


http://www.ppmy.cn/ops/32538.html

相关文章

快速了解Django:核心概念解析与实践指南

title: 快速了解Django&#xff1a;核心概念解析与实践指南 date: 2024/5/1 20:31:41 updated: 2024/5/1 20:31:41 categories: 后端开发 tags: Django核心路由系统视图系统ORM管理中间件Web框架登录装饰器 第一章&#xff1a;Django简介 背景和发展历程&#xff1a; Djan…

Python | Leetcode Python题解之第65题有效数字

题目&#xff1a; 题解&#xff1a; from enum import Enumclass Solution:def isNumber(self, s: str) -> bool:State Enum("State", ["STATE_INITIAL","STATE_INT_SIGN","STATE_INTEGER","STATE_POINT","STATE_…

Android 安装过程三 MSG_ON_SESSION_SEALED、MSG_STREAM_VALIDATE_AND_COMMIT的处理

Android 安装过程一 界面跳转 知道&#xff0c;在InstallInstalling Activity中&#xff0c;PackageInstallerSession对象创建之后&#xff0c;接着会打开它&#xff0c;然后将安装文件进行拷贝&#xff0c;拷贝完成之后&#xff0c;会对Session对象确认。   从Session对象确…

python基础第29课《阶段检测》

第29课《阶段检测》 1.下面哪个选项的说法是错误的是 A、print()是输出指令 B、print(“”&#xff0c;end “”)中的end ""是不换行操作c、input()是输入指令 D、输出指令和输入指令必须结合使用 选项 D 的说法是错误的。输出指令&#xff08;如 print()&#xff…

2024五一杯数学建模ABC题(附历年优秀论文+写作模板)参考论文+完整代码数据集

2024年第二十一届五一数学建模竞赛 资料思路分享群:937571119 一、赛题思路 (赛题出来以后第一时间在群内分享) 二、比赛日期和时间 比赛开始时间:2024年5月1日(周三)10;00 比赛结束时间:2024年5月4日(周六&#xff09;12:00 竞赛信息 数学建模竞赛是一项模拟面对实际问题…

A Bug‘s Life (并查集)

//新生训练 #include <iostream> #include <algorithm> using namespace std; const int N 5000; int p[N], sz[N]; int n, m; int find(int x) {if (p[x] ! x)p[x] find(p[x]);return p[x]; } int main() {int T;scanf("%d", &T);for (int k 1; …

uni-app(优医咨询)项目实战 - 第3天

学习目标: 掌握 luch-request 网络请求的用法 能够对 Pinia 进行初始化操作 掌握创建 Store 及数据操作的步骤 能够对 Pinia 数据进行持久化的处理 掌握用户登录的实现方法 一、项目启动 从零起步创建项目,完整的静态页面可以从 gitee 仓库获取。 1.1 创建项目 以 HBuilde…

迎接AI时代:智能科技的社会责任与未来展望

AI智能体的社会角色、伦理挑战与可持续发展路径 引言&#xff1a; 在技术的浪潮中&#xff0c;AI智能体正逐步成为我们生活的一部分。它们在医疗、教育、交通等领域的应用&#xff0c;预示着一个全新的时代即将到来。本文将结合实际案例和数据分析&#xff0c;深入探讨AI智能体…