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

JAVA:常见 JSON 库的技术详解

1、简述

在现代应用开发中,JSON(JavaScript Object Notation)已成为数据交换的标准格式。Java 提供了多种方式将对象转换为 JSON 或从 JSON 转换为对象,常见的库包括 Jackson、Gson 和 org.json。本文将介绍几种常用的 JSON 处理方式,并通过简单示例展示其应用。

在这里插入图片描述

2、什么是 JSON?

JSON 是一种轻量级的数据交换格式,使用键值对来表示数据。它易于人阅读和编写,同时也易于机器解析和生成。常见的 JSON 数据结构如下:

{"name": "John","age": 30,"address": {"city": "New York","zip": "10001"}
}

3、常见的JSON 库

3.1 使用 Jackson 进行 JSON 转换

Jackson 是 Java 中最流行的 JSON 解析库之一。它提供了强大的数据绑定功能,支持将 Java 对象与 JSON 之间进行转换。要使用 Jackson,请在 pom.xml 中添加以下依赖:

<dependency><groupId>com.fasterxml.jackson.core</groupId><artifactId>jackson-databind</artifactId><version>2.13.0</version>
</dependency>

示例代码:

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;public class JacksonExample {public static void main(String[] args) throws JsonProcessingException {// 创建 Person 对象Person person = new Person("John", 30, new Address("New York", "10001"));// 序列化:将对象转换为 JSONObjectMapper objectMapper = new ObjectMapper();String jsonString = objectMapper.writeValueAsString(person);System.out.println("Serialized JSON: " + jsonString);// 反序列化:将 JSON 转换为对象Person deserializedPerson = objectMapper.readValue(jsonString, Person.class);System.out.println("Deserialized Person: " + deserializedPerson);}
}class Person {private String name;private int age;private Address address;// 构造函数、getters、setters、toString 省略
}class Address {private String city;private String zip;// 构造函数、getters、setters、toString 省略
}
3.2 使用 Gson 进行 JSON 转换

Gson 是 Google 提供的轻量级 JSON 处理库,它可以将 Java 对象与 JSON 字符串相互转换。要使用 Gson,请在 pom.xml 中添加以下依赖:

<dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId><version>2.8.8</version>
</dependency>

示例代码:

import com.google.gson.Gson;public class GsonExample {public static void main(String[] args) {// 创建 Person 对象Person person = new Person("John", 30, new Address("New York", "10001"));// 序列化:将对象转换为 JSONGson gson = new Gson();String jsonString = gson.toJson(person);System.out.println("Serialized JSON: " + jsonString);// 反序列化:将 JSON 转换为对象Person deserializedPerson = gson.fromJson(jsonString, Person.class);System.out.println("Deserialized Person: " + deserializedPerson);}
}class Person {private String name;private int age;private Address address;// 构造函数、getters、setters、toString 省略
}class Address {private String city;private String zip;// 构造函数、getters、setters、toString 省略
}
3.3 使用 org.json 进行 JSON 处理

org.json 是 Java 原生的 JSON 处理库,适用于处理简单的 JSON 数据。要使用 org.json,请在 pom.xml 中添加以下依赖:

<dependency><groupId>org.json</groupId><artifactId>json</artifactId><version>20210307</version>
</dependency>

示例代码:

import org.json.JSONObject;public class OrgJsonExample {public static void main(String[] args) {// 创建 Person 对象的 JSON 字符串String jsonString = "{ \"name\": \"John\", \"age\": 30, \"address\": { \"city\": \"New York\", \"zip\": \"10001\" } }";// 解析 JSON 字符串JSONObject jsonObject = new JSONObject(jsonString);System.out.println("Name: " + jsonObject.getString("name"));System.out.println("Age: " + jsonObject.getInt("age"));JSONObject address = jsonObject.getJSONObject("address");System.out.println("City: " + address.getString("city"));System.out.println("Zip: " + address.getString("zip"));// 创建 JSON 对象JSONObject newPerson = new JSONObject();newPerson.put("name", "Jane");newPerson.put("age", 28);JSONObject newAddress = new JSONObject();newAddress.put("city", "Los Angeles");newAddress.put("zip", "90001");newPerson.put("address", newAddress);System.out.println("Created JSON: " + newPerson.toString());}
}
3.4 使用 JSON-B 进行 JSON 转换

JSON-B 是 Jakarta EE 提供的标准 JSON 绑定库,专为 Java 开发的 JSON 序列化和反序列化标准。要使用 JSON-B,请在 pom.xml 中添加以下依赖:

<dependency><groupId>javax.json.bind</groupId><artifactId>javax.json.bind-api</artifactId><version>1.0</version>
</dependency>

示例代码:

import javax.json.bind.Jsonb;
import javax.json.bind.JsonbBuilder;public class JsonBExample {public static void main(String[] args) {// 创建 Person 对象Person person = new Person("John", 30, new Address("New York", "10001"));// 序列化:将对象转换为 JSONJsonb jsonb = JsonbBuilder.create();String jsonString = jsonb.toJson(person);System.out.println("Serialized JSON: " + jsonString);// 反序列化:将 JSON 转换为对象Person deserializedPerson = jsonb.fromJson(jsonString, Person.class);System.out.println("Deserialized Person: " + deserializedPerson);}
}class Person {private String name;private int age;private Address address;// 构造函数、getters、setters、toString 省略
}class Address {private String city;private String zip;// 构造函数、getters、setters、toString 省略
}
3.5 Moshi

Moshi 是 Square 公司提供的一款轻量级 JSON 库,专注于简单性和性能。它与 Gson 类似,但它在设计上更加严谨,并且更容易扩展。

import com.squareup.moshi.JsonAdapter;
import com.squareup.moshi.Moshi;public class MoshiExample {public static void main(String[] args) throws Exception {// 创建 Moshi 实例Moshi moshi = new Moshi.Builder().build();JsonAdapter<Person> jsonAdapter = moshi.adapter(Person.class);// 序列化Person person = new Person("John", 30, new Address("New York", "10001"));String jsonString = jsonAdapter.toJson(person);System.out.println("Serialized JSON: " + jsonString);// 反序列化Person deserializedPerson = jsonAdapter.fromJson(jsonString);System.out.println("Deserialized Person: " + deserializedPerson);}
}

Moshi 强调简洁,同时支持 Kotlin 更加无缝的集成。

3.6 Flexjson

Flexjson 是一个快速和轻量的 JSON 库,专注于 Java 对象到 JSON 的序列化以及 JSON 到 Java 对象的反序列化。它允许你对序列化的字段进行高度控制,适合需要进行部分序列化或者处理复杂嵌套数据结构的场景。

import flexjson.JSONDeserializer;
import flexjson.JSONSerializer;public class FlexjsonExample {public static void main(String[] args) {// 创建 Person 对象Person person = new Person("John", 30, new Address("New York", "10001"));// 序列化JSONSerializer serializer = new JSONSerializer();String jsonString = serializer.serialize(person);System.out.println("Serialized JSON: " + jsonString);// 反序列化JSONDeserializer<Person> deserializer = new JSONDeserializer<>();Person deserializedPerson = deserializer.deserialize(jsonString, Person.class);System.out.println("Deserialized Person: " + deserializedPerson);}
}

Flexjson 在复杂序列化需求时非常有用,比如需要不同的视图或包含/排除字段的序列化操作。

3.7 Json-simple

Json-simple 是一个简单、轻量级的 JSON 库,适合处理基本的 JSON 操作。虽然它的功能较为基础,但它的 API 非常简单,适合处理小型或快速开发场景。

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;public class JsonSimpleExample {public static void main(String[] args) throws Exception {// 创建 JSON 对象JSONObject person = new JSONObject();person.put("name", "John");person.put("age", 30);JSONObject address = new JSONObject();address.put("city", "New York");address.put("zip", "10001");person.put("address", address);// 序列化System.out.println("Serialized JSON: " + person.toJSONString());// 反序列化JSONParser parser = new JSONParser();JSONObject deserializedPerson = (JSONObject) parser.parse(person.toJSONString());System.out.println("Deserialized JSON: " + deserializedPerson);}
}

Json-simple 适合做简单的 JSON 解析,API 设计简洁但功能有限,适合小规模应用。

3.8 Jsoniter (Json-iterator)

Jsoniter 是一个性能优异的 JSON 库,其解析和序列化性能比 Jackson 还要快。它的优势在于处理大规模数据时速度非常快,适合高性能需求的场景。

import com.jsoniter.JsonIterator;
import com.jsoniter.output.JsonStream;public class JsoniterExample {public static void main(String[] args) {// 序列化Person person = new Person("John", 30, new Address("New York", "10001"));String jsonString = JsonStream.serialize(person);System.out.println("Serialized JSON: " + jsonString);// 反序列化Person deserializedPerson = JsonIterator.deserialize(jsonString, Person.class);System.out.println("Deserialized Person: " + deserializedPerson);}
}

Jsoniter 非常注重性能,适用于对速度和内存使用要求非常高的场景。

3.9 Jettison

Jettison 是一个基于 StAX 的库,用于将 XML 转换为 JSON 或将 JSON 转换为 XML。它主要用于与 JSON 和 XML 之间相互转换的数据交换场景。

import org.codehaus.jettison.json.JSONObject;public class JettisonExample {public static void main(String[] args) throws Exception {// 创建 JSON 对象JSONObject person = new JSONObject();person.put("name", "John");person.put("age", 30);JSONObject address = new JSONObject();address.put("city", "New York");address.put("zip", "10001");person.put("address", address);// 序列化输出System.out.println("Serialized JSON: " + person.toString());}
}

Jettison 主要用于解决与 XML 兼容的问题,适合需要同时处理这两种格式的数据应用。

3.10 Boon

Boon 是一个快速的 JSON 库,专注于速度和易用性。它支持简单的 API 来处理 JSON 数据,并且以其高速性能为特点。

import org.boon.Boon;public class BoonExample {public static void main(String[] args) {// 序列化Person person = new Person("John", 30, new Address("New York", "10001"));String jsonString = Boon.toJson(person);System.out.println("Serialized JSON: " + jsonString);// 反序列化Person deserializedPerson = Boon.fromJson(jsonString, Person.class);System.out.println("Deserialized Person: " + deserializedPerson);}
}

Boon 提供了非常快速的 JSON 处理能力,适合需要高性能和易用性的场景。

4、总结

Java 提供了多种方式来处理 JSON 数据,每种库都有其独特的优势,除了常见的 Jackson 和 Gson,还有一些轻量级的 JSON 库如 Moshi、Flexjson 和 Json-simple,适合特定的场景。例如,Moshi 在与 Kotlin 集成时非常流畅,Jsoniter 在性能上非常出色,而 Flexjson 则在需要灵活控制序列化时表现优异。根据项目的需求选择合适的 JSON 处理库,可以帮助更高效地进行开发。

相关文章:

JAVA:常见 JSON 库的技术详解

1、简述 在现代应用开发中&#xff0c;JSON&#xff08;JavaScript Object Notation&#xff09;已成为数据交换的标准格式。Java 提供了多种方式将对象转换为 JSON 或从 JSON 转换为对象&#xff0c;常见的库包括 Jackson、Gson 和 org.json。本文将介绍几种常用的 JSON 处理…...

Redis缓存击穿、雪崩、穿透解决方案

Redis 缓存击穿、雪崩、穿透解决方案 1、首先看看逻辑方面是否还有优化空间&#xff0c;正常流程查询redis中获取不到数据&#xff0c;则去数据库获取&#xff0c;但数据库查询并返回时&#xff0c;调用异步方法&#xff0c;将该数据存储进redis中&#xff0c;并设置一个较短的…...

C++ 优先算法——盛最多水的容器(双指针)

目录 题目&#xff1a;盛最多水的容器 1. 题目解析 2. 算法原理 3. 代码实现 题目&#xff1a;盛最多水的容器 1. 题目解析 题目截图: 如图所示&#xff1a; 水的高度一定是由较低的那条线的高度决定的&#xff1a;例1图中&#xff0c;是由7决定的&#xff0c;然后求出…...

blender 小车建模 建模 学习笔记

一、学习blender视频教程链接 案例4&#xff1a;狂奔的小车_建模_哔哩哔哩_bilibilihttps://www.bilibili.com/video/BV1Bt4y1E7qn?p14&spm_id_from333.788.videopod.episodes&vd_sourced0ea58f1127eed138a4ba5421c577eb1 二、开始建模 &#xff08;1&#xff09;创…...

导出列表数据到Excel并下载

Java导出查询到的数据列表为Excel并下载 1.背景 工作中经常有需求&#xff0c;需要把列表的数据导出为Excel并下载。EasyExcel工具可以很好的实现这一需求。 2.实现流程 1.引入EasyExcel依赖包 <dependency><groupId>com.alibaba</groupId><artifactId…...

基于NVIDIA NIM平台实现盲人过马路的demo(一)

前言:利用NVIDIA NIM平台提供的大模型进行编辑,通过llama-3.2-90b-vision-instruct模型进行初步的图片检测 step1: 部署大模型到本地,引用所需要的库 import os import requests import base64 import cv2 import time from datetime import datetimestep2: 观看官方使用文…...

美格智能5G车规级通信模组:以连接+算力驱动智能化进阶

2023年3月&#xff0c;基于高通公司第二代骁龙汽车5G调制解调器及射频系统平台SA522M/SA525M&#xff0c;美格智能在德国纽伦堡嵌入式系统展上正式发布全新一代5G车规级C-V2X通信模组MA922系列&#xff0c;迅速引起行业和市场关注。随着5G高速网联逐步成为智能汽车标配&#xf…...

[MRCTF2020]PYWebsite1

如果输入的密钥是对的那么我们就直接跳转到flag.php页面 那么我们直接访问&#x1f60e;&#xff0c;他不带我们去我们自己去. 那就用XFF呗. 知识点&#xff1a; 定义&#xff1a;X-Forwarded-For是一个HTTP请求头字段&#xff0c;用于识别通过HTTP代理或负载均衡方式连接到W…...

无源元器件-磁珠选型参数总结

🏡《总目录》 目录 1,概述2,磁珠选型参数2.1,电学参数2.1.3,阻抗(Impedance)2.1.2,额定电流(Rated Current)2.1.3,直流电阻(DC Resistance)2.2,机械性能参数2.2.1,外观和尺寸(Appearance and Dimensions)2.2.2,粘接强度( Bonding Strength)2.2.3,弯曲强度…...

宝顶白芽,慢生活的味觉盛宴

在快节奏的生活中&#xff0c;人们愈发向往那种悠然自得、返璞归真的生活方式。白茶&#xff0c;以其独特的韵味和清雅的风格&#xff0c;成为了现代人追求心灵宁静与生活品质的象征。而在众多白茶之中&#xff0c;竹叶青茶业出品的宝顶白芽以其甘甜醇爽的特质&#xff0c;成为…...

已知三角形三边长求面积用仓颉语言作答

仓颉语言 https://cangjie-lang.cn/ linux和win和mac均有sdk&#xff0c;在本机deepinlinuxv23下载到本地解压缩到目录下设置环境变量 source envsetup.sh 比java方便太多了&#xff0c;java每次都是要自己搞很久&#xff0c;当然&#xff0c;打开看一下envsertup.sh,和我们…...

【JavaScript】匿名函数及回调函数总结

JavaScript 匿名函数 匿名函数没有显式的名称, 被视为一个函数表达式&#xff0c;可以在不需要额外命名的情况下进行定义和使用, 通常被用作回调函数, 即将函数作为参数传递给其他函数。 回调函数是在特定事件或条件发生时被调用的函数&#xff0c;回调函数通常用于异步编程中…...

HTML鼠标移动的波浪线动画——页面将会初始化一个Canvas元素,并使用JavaScript代码在Canvas上绘制响应鼠标移动的波浪线动画

代码如下 <!DOCTYPE html> <html lang"en"> <head><meta charset"UTF-8"><meta name"viewport" content"widthdevice-width, initial-scale1.0"><title>Wave Animation</title><style&…...

树莓派开发相关知识八-其他传感器

1、蜂鸣器 #!/usr/bin/env python #coding:utf-8import RPi.GPIO as GPIO import time OUT5 def init():GPIO.setwarnings(False)GPIO.setmode(GPIO.BCM)GPIO.setup(OUT,GPIO.OUT)#蜂鸣器鸣叫函数 def beep(seconds):GPIO.output(OUT,GPIO.HIGH)time.sleep(seconds)GPIO.output…...

ComfyUI - ComfyUI 工作流中集成 SAM2 + GroundingDINO 处理图像与视频 教程

欢迎关注我的CSDN&#xff1a;https://spike.blog.csdn.net/ 本文地址&#xff1a;https://spike.blog.csdn.net/article/details/143359538 免责声明&#xff1a;本文来源于个人知识与公开资料&#xff0c;仅用于学术交流&#xff0c;欢迎讨论&#xff0c;不支持转载。 SAM2 与…...

STM32G4 双ADC模式之常规同步模式独立注入模式

目录 概述 1 认识双ADC模式 2 功能实现 2.1 原理介绍 2.2 实现方法 概述 本文主要介绍STM32G4 双ADC模式之常规同步模式&独立注入模式相关内容&#xff0c;包括ADC模块的功能介绍&#xff0c;实现框架结构&#xff0c;以及常规同步模式&独立注入模式ADC的转换的实…...

深入理解网络协议:OSPF、VLAN、NAT与ACL详解

OSPF工作过程与基础配置 一、OSPF的工作过程 OSPF&#xff08;开放最短路径优先&#xff09;是一个广泛使用的路由协议&#xff0c;它的工作过程可以总结为以下几个步骤&#xff1a; 启动与邻居发现 OSPF在配置完成后&#xff0c;会通过本地组播地址224.0.0.5发送HELLO包。HE…...

idea 配置tomcat 服务

选择tomcat的安装路径 选到bin的文件夹的上一层就行...

.net core 接口,动态接收各类型请求的参数

[HttpPost] public async Task<IActionResult> testpost([FromForm] object info) { //Postman工具测试结果&#xff1a; //FromBody,Postman的body只有rawjson时才进的来 //参数为空时&#xff0c;Body(form-data、x-www-form-urlencoded)解析到的数据也有所…...

关注!这些型号SSD有Windows蓝屏问题需要修复

近期&#xff0c;在闪迪官方有一个SSD FW升级提醒&#xff0c;主要是为了解决Windows 11 24H2系统蓝屏的问题&#xff1a; Fix问题&#xff1a;这些SSD的主机内存缓冲区&#xff08;Host Memory Buffer&#xff0c;简称HMB&#xff09;功能可能会导致系统出现蓝屏死机&#xff…...

Redis相关知识总结(缓存雪崩,缓存穿透,缓存击穿,Redis实现分布式锁,如何保持数据库和缓存一致)

文章目录 1.什么是Redis&#xff1f;2.为什么要使用redis作为mysql的缓存&#xff1f;3.什么是缓存雪崩、缓存穿透、缓存击穿&#xff1f;3.1缓存雪崩3.1.1 大量缓存同时过期3.1.2 Redis宕机 3.2 缓存击穿3.3 缓存穿透3.4 总结 4. 数据库和缓存如何保持一致性5. Redis实现分布式…...

LeetCode - 394. 字符串解码

题目 394. 字符串解码 - 力扣&#xff08;LeetCode&#xff09; 思路 使用两个栈&#xff1a;一个存储重复次数&#xff0c;一个存储字符串 遍历输入字符串&#xff1a; 数字处理&#xff1a;遇到数字时&#xff0c;累积计算重复次数左括号处理&#xff1a;保存当前状态&a…...

《通信之道——从微积分到 5G》读书总结

第1章 绪 论 1.1 这是一本什么样的书 通信技术&#xff0c;说到底就是数学。 那些最基础、最本质的部分。 1.2 什么是通信 通信 发送方 接收方 承载信息的信号 解调出其中承载的信息 信息在发送方那里被加工成信号&#xff08;调制&#xff09; 把信息从信号中抽取出来&am…...

Keil 中设置 STM32 Flash 和 RAM 地址详解

文章目录 Keil 中设置 STM32 Flash 和 RAM 地址详解一、Flash 和 RAM 配置界面(Target 选项卡)1. IROM1(用于配置 Flash)2. IRAM1(用于配置 RAM)二、链接器设置界面(Linker 选项卡)1. 勾选“Use Memory Layout from Target Dialog”2. 查看链接器参数(如果没有勾选上面…...

今日科技热点速览

&#x1f525; 今日科技热点速览 &#x1f3ae; 任天堂Switch 2 正式发售 任天堂新一代游戏主机 Switch 2 今日正式上线发售&#xff0c;主打更强图形性能与沉浸式体验&#xff0c;支持多模态交互&#xff0c;受到全球玩家热捧 。 &#x1f916; 人工智能持续突破 DeepSeek-R1&…...

动态 Web 开发技术入门篇

一、HTTP 协议核心 1.1 HTTP 基础 协议全称 &#xff1a;HyperText Transfer Protocol&#xff08;超文本传输协议&#xff09; 默认端口 &#xff1a;HTTP 使用 80 端口&#xff0c;HTTPS 使用 443 端口。 请求方法 &#xff1a; GET &#xff1a;用于获取资源&#xff0c;…...

Golang——7、包与接口详解

包与接口详解 1、Golang包详解1.1、Golang中包的定义和介绍1.2、Golang包管理工具go mod1.3、Golang中自定义包1.4、Golang中使用第三包1.5、init函数 2、接口详解2.1、接口的定义2.2、空接口2.3、类型断言2.4、结构体值接收者和指针接收者实现接口的区别2.5、一个结构体实现多…...

DiscuzX3.5发帖json api

参考文章&#xff1a;PHP实现独立Discuz站外发帖(直连操作数据库)_discuz 发帖api-CSDN博客 简单改造了一下&#xff0c;适配我自己的需求 有一个站点存在多个采集站&#xff0c;我想通过主站拿标题&#xff0c;采集站拿内容 使用到的sql如下 CREATE TABLE pre_forum_post_…...

macOS 终端智能代理检测

&#x1f9e0; 终端智能代理检测&#xff1a;自动判断是否需要设置代理访问 GitHub 在开发中&#xff0c;使用 GitHub 是非常常见的需求。但有时候我们会发现某些命令失败、插件无法更新&#xff0c;例如&#xff1a; fatal: unable to access https://github.com/ohmyzsh/oh…...

在 Visual Studio Code 中使用驭码 CodeRider 提升开发效率:以冒泡排序为例

目录 前言1 插件安装与配置1.1 安装驭码 CodeRider1.2 初始配置建议 2 示例代码&#xff1a;冒泡排序3 驭码 CodeRider 功能详解3.1 功能概览3.2 代码解释功能3.3 自动注释生成3.4 逻辑修改功能3.5 单元测试自动生成3.6 代码优化建议 4 驭码的实际应用建议5 常见问题与解决建议…...