当前位置: 首页 > news >正文

JSON解析

目录

一、 JSON简介

二、 JSON语法

三、 JSON的用途

四、Java解析JSON

五、使用Fastjson


一、 JSON简介

   JSON是一种轻量级的数据交换格式。它基于 ECMAScriptEuropean 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());}}
}

http://www.dtcms.com/a/303751.html

相关文章:

  • Spring IOC 基于Cglib实现含构造函数的类实例化策略
  • 循环神经网络——动手学深度学习7
  • 板凳-------Mysql cookbook学习 (十二--------7)
  • SpringBoot 的@Repository 等注解的底层实现原理
  • 智能体安全与可信AI:防护机制与伦理考量
  • SpringBoot之起步依赖
  • 【使用python中列表注意事项】
  • Windows使用Powershell自动安装SqlServer2025服务器与SSMS管理工具
  • 【自存用】mumu模拟器+mitmproxy配置
  • ADSP-21565的SigmaStudio图形化编程详解
  • Linux 完整删除 Systemd 服务的步骤
  • 递归、搜索与回溯算法核心思想解析
  • Agent常用搜索引擎Tavily使用学习
  • linux中简易云盘系统项目实战:基于 TCP协议的 Socket 通信、json数据交换、MD5文件区别与多用户文件管理实现
  • 配置daemon.json使得 Docker 容器能够使用服务器GPU【验证成功】
  • 界面控件Telerik UI for WPF 2025 Q2亮点 - 重要组件全新升级
  • 「源力觉醒 创作者计划」_文心大模型 4.5 多模态实测:开源加速 AI 普惠落地
  • VUE -- 基础知识讲解(一)
  • 从字符串中“薅出”最长子串:LeetCode 340 Swift 解法全解析
  • 分布式链路追踪详解
  • 如何用USRP捕获手机信号波形(中)手机/基站通信
  • Java面试宝典:MySQL8新特性底层原理
  • 设计模式:状态模式 State
  • 【Redis实现基础的分布式锁及Lua脚本说明】
  • 【CAN总线】STM32 的 CAN 总线通信开发笔记(基于 HAL)
  • Spring Boot 自动配置:从 2.x 到 3.x 的进化之路
  • Python 程序设计讲义(28):字符串的用法——格式化字符串
  • 【C++】第十九节—一文万字详解 | AVL树实现
  • Go进阶:流程控制(if/for/switch)与数组切片
  • adb reboot 与 adb shell svc power reboot 的区别