JSON解析

devtools/2024/9/24 13:20:03/

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/devtools/32979.html

相关文章

分割回文串(力扣131)

解题思路&#xff1a;仍就是上递归三部曲&#xff0c;但于此同时要明白此时的index就可以作为切割回文串的线了 具体代码如下&#xff1a; class Solution { private: vector<vector<string>> result; vector<string> path; // 放已经回文的子串 void back…

关机恶搞小程序

1. system("shutdown")的介绍 当system函数的参数是"shutdown"时&#xff0c;它将会执行系统的关机命令。 具体来说&#xff0c;system("shutdown")的功能是向操作系统发送一个关机信号&#xff0c;请求关闭计算机。这将触发操作系统执行一系列…

求矩阵对角线元素之和(C语言)

一、N-S流程图&#xff1b; 二、运行结果&#xff1b; 三、源代码&#xff1b; # define _CRT_SECURE_NO_WARNINGS # include <stdio.h>int main() {//初始化变量值&#xff1b;int i 0;int j 0;int sum 0;int a[3][3] { 0 };//获取数组a的值&#xff1b;printf(&qu…

c++多线程2小时速成

简介 c多线程基础需要掌握这三个标准库的使用&#xff1a;std::thread,std::mutex, andstd::async。 1. Hello, world #include <iostream> #include <thread>void hello() { std::cout << "Hello Concurrent World!\n"; }int main() {std::th…

Pop_OS 个人配置

Pop_OS 个人配置 系统优化 DNS 配置 小技巧&#xff1a; 使用 阿里云 免费 DNS 可以有效解决 GitHub 访问问题 IP4 223.5.5.5 223.6.6.6IP6 2400:3200::1 2400:3200:baba::1Ubuntu 镜像 使用 华为云 提供的 Ubunut 镜像 sudo sed -i "shttp://apt.pop-os.orghttp://…

OceanBase 分布式数据库【信创/国产化】- OceanBase 平台产品 - 迁移评估工具 OMA

本心、输入输出、结果 文章目录 OceanBase 分布式数据库【信创/国产化】- OceanBase 平台产品 - 迁移评估工具 OMA前言OceanBase 数据更新架构OceanBase 平台产品 - 迁移评估工具 OMA兼容性评估性能评估导出 OceanBase 数据库对象和 SQL 语句OceanBase 分布式数据库【信创/国产…

内核workqueue框架

workqueue驱动的底半部实现方式之一就是工作队列&#xff0c;作为内核的标准模块&#xff0c;它的使用接口也非常简单&#xff0c;schedule_work或者指定派生到哪个cpu的schedule_work_on。 还有部分场景会使用自定义的workqueue&#xff0c;这种情况会直接调用queue_work和qu…

双fifo流水线操作——verilog练习与设计

文章目录 一、案例分析二、fifo_ctrl模块设计2.1 波形设计&#xff1a;2.2 代码实现2.2.1 fifo_ctrl2.2.2 顶层文件top_fifo_ctrl&#xff08;rx和tx模块省略&#xff09;2.2.3 仿真文件tb_fifo_ctrl 2.3波形仿真 一、案例分析 案例要求&#xff1a;写一个 fifo 控制器&#x…