Java常用的几种JSON解析工具-程序员宅基地

技术标签: Java  java  json  开发语言  

一、Gson:Google开源的JSON解析库

1.添加依赖

<!--gson-->
<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
</dependency>
<!--lombok-->
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
</dependency>
toJson:用于序列化,对象转Json数据
fromJson:用于反序列化,把Json数据转成对象

示例代码如下:

import lombok.*;

/**
 * @author qinxun
 * @date 2023-05-30
 * @Descripion: 学生实体类
 */
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Student {

    private Long termId;
    private Long classId;
    private Long studentId;
    private String name;

}
import com.example.quartzdemo.entity.Student;
import com.google.gson.Gson;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

/**
 * @author qinxun
 * @date 2023-06-09
 * @Descripion: Gson测试
 */
@SpringBootTest
public class GsonTest {

    @Test
    void test1() {
        Student student = new Student(1L, 2L, 2L, "张三");
        Gson gson = new Gson();
        // 输出{"termId":1,"classId":2,"studentId":2,"name":"张三"}
        System.out.println(gson.toJson(student));

        String data = "{\"termId\":2,\"classId\":2,\"studentId\":2,\"name\":\"李四\"}";
        Student studentData = gson.fromJson(data, Student.class);
        // 输出Student(termId=2, classId=2, studentId=2, name=李四)
        System.out.println(studentData);
    }
}

二、fastjson:阿里巴巴开源的JSON解析库

1.添加依赖

<!--fastjson-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.83</version>
</dependency>

JSON.toJSONString(obj):用于序列化对象,转成json数据。

JSON.parseObject(obj,class): 用于反序列化对象,转成数据对象。

JSON.parseArray():把 JSON 字符串转成集合

示例代码如下:

mport com.alibaba.fastjson.JSON;
import com.example.quartzdemo.entity.Student;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

/**
 * @author qinxun
 * @date 2023-06-09
 * @Descripion: fastjson测试
 */
@SpringBootTest
public class FastJsonTest {

    @Test
    void test1() {
        Student student = new Student(1L, 2L, 2L, "张三");
        String json = JSON.toJSONString(student);
        // 输出{"classId":2,"name":"张三","studentId":2,"termId":1}
        System.out.println(json);

        String data = "{\"termId\":2,\"classId\":2,\"studentId\":2,\"name\":\"李四\"}";
        Student student1 = JSON.parseObject(data, Student.class);
        // 输出Student(termId=2, classId=2, studentId=2, name=李四)
        System.out.println(student1);

        String arrStr = "[{\"termId\":2,\"classId\":2,\"studentId\":2,\"name\":\"李四\"},{\"termId\":1,\"classId\":2,\"studentId\":2,\"name\":\"张三\"}]";
        List<Student> studentList = JSON.parseArray(arrStr, Student.class);
        // 输出[Student(termId=2, classId=2, studentId=2, name=李四), Student(termId=1, classId=2, studentId=2, name=张三)]
        System.out.println(studentList);
    }
}

2.使用注解

有时候,你的 JSON 字符串中的 key 可能与 Java 对象中的字段不匹配,比如大小写;有时候,你需要指定一些字段序列化但不反序列化;有时候,你需要日期字段显示成指定的格式。

我们只需要在对应的字段上加上 @JSONField 注解就可以了。

name 用来指定字段的名称,format 用来指定日期格式,serialize 和 deserialize 用来指定是否序列化和反序列化。

public @interface JSONField {
    String name() default "";
    String format() default "";
    boolean serialize() default true;
    boolean deserialize() default true;
}
import com.alibaba.fastjson.annotation.JSONField;
import lombok.*;

import java.util.Date;

/**
 * @author qinxun
 * @date 2023-05-30
 * @Descripion: 学生实体类
 */
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Student {

    private Long termId;
    private Long classId;
    @JSONField(serialize = false, deserialize = true)
    private Long studentId;
    private String name;

    @JSONField(format = "yyyy年MM月dd日")
    private Date birthday;

}

我们设置studentId不支持序列化,但是支持反序列化。

测试示例代码如下:

import com.alibaba.fastjson.JSON;
import com.example.quartzdemo.entity.Student;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Date;
import java.util.List;

/**
 * @author qinxun
 * @date 2023-06-09
 * @Descripion: fastjson测试
 */
@SpringBootTest
public class FastJsonTest {

    @Test
    void test1() {
        Student student = new Student(1L, 2L, 2L, "张三", new Date());
        String json = JSON.toJSONString(student);
        // 输出{"birthday":"2023年06月09日","classId":2,"name":"张三","termId":1}
        System.out.println(json);

        String data = "{\"termId\":2,\"classId\":2,\"studentId\":2,\"name\":\"李四\"}";
        Student student1 = JSON.parseObject(data, Student.class);
        // 输出Student(termId=2, classId=2, studentId=2, name=李四, birthday=null)
        System.out.println(student1);

        String arrStr = "[{\"termId\":2,\"classId\":2,\"studentId\":2,\"name\":\"李四\"},{\"termId\":1,\"classId\":2,\"studentId\":2,\"name\":\"张三\"}]";
        List<Student> studentList = JSON.parseArray(arrStr, Student.class);
        // 输出[Student(termId=2, classId=2, studentId=2, name=李四, birthday=null), Student(termId=1, classId=2, studentId=2, name=张三, birthday=null)]
        System.out.println(studentList);
    }
}

执行结果:

{"birthday":"2023年06月09日","classId":2,"name":"张三","termId":1}
Student(termId=2, classId=2, studentId=2, name=李四, birthday=null)
[Student(termId=2, classId=2, studentId=2, name=李四, birthday=null), Student(termId=1, classId=2, studentId=2, name=张三, birthday=null)]

我们发现studentId没有被序列化成json数据。birthday生成了自定义的数据格式。

三、Jackson:SpringBoot默认的JSON解析工具

1.添加依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

我们添加默认的web依赖就自动的添加了Jackson的依赖。

2.序列化

  • writeValueAsString(Object value) 方法,将对象存储成字符串
  • writeValueAsBytes(Object value) 方法,将对象存储成字节数组
  • writeValue(File resultFile, Object value) 方法,将对象存储成文件

示例代码如下:

import lombok.*;

/**
 * @author qinxun
 * @date 2023-06-09
 * @Descripion:
 */
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Writer {

    private String name;
    private int age;

}
import com.example.quartzdemo.bean.Writer;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

/**
 * @author qinxun
 * @date 2023-06-09
 * @Descripion:
 */
@SpringBootTest
public class JacksonTest {

    @Test
    void test1() throws JsonProcessingException {
        Writer writer = new Writer("qx", 25);
        ObjectMapper mapper = new ObjectMapper();
        String jsonStr = mapper.writerWithDefaultPrettyPrinter()
                .writeValueAsString(writer);
        System.out.println(jsonStr);
    }
}

执行结果:

{
  "name" : "qx",
  "age" : 25
}

不是所有的字段都支持序列化和反序列化,需要符合以下规则:

  • 如果字段的修饰符是 public,则该字段可序列化和反序列化(不是标准写法)。
  • 如果字段的修饰符不是 public,但是它的 getter 方法和 setter 方法是 public,则该字段可序列化和反序列化。getter 方法用于序列化,setter 方法用于反序列化。
  • 如果字段只有 public 的 setter 方法,而无 public 的 getter 方 法,则该字段只能用于反序列化。

3.反序列化

  • readValue(String content, Class<T> valueType) 方法,将字符串反序列化为 Java 对象
  • readValue(byte[] src, Class<T> valueType) 方法,将字节数组反序列化为 Java 对象
  • readValue(File src, Class<T> valueType) 方法,将文件反序列化为 Java 对象

示例代码如下:

import com.example.quartzdemo.bean.Writer;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

/**
 * @author qinxun
 * @date 2023-06-09
 * @Descripion:
 */
@SpringBootTest
public class JacksonTest {

    @Test
    void test1() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        String jsonString = "{\n" +
                "  \"name\" : \"qx\",\n" +
                "  \"age\" : 18\n" +
                "}";
        Writer writer = mapper.readValue(jsonString, Writer.class);
        // 输出Writer(name=qx, age=18)
        System.out.println(writer);
    }
}

借助 TypeReference 可以将 JSON 字符串数组转成泛型 List

示例代码如下:

import com.example.quartzdemo.bean.Writer;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.List;

/**
 * @author qinxun
 * @date 2023-06-09
 * @Descripion:
 */
@SpringBootTest
public class JacksonTest {

    @Test
    void test1() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        String json = "[{ \"name\" : \"张三\", \"age\" : 18 }, { \"name\" : \"李四\", \"age\" : 19 }]";
        List<Writer> writerList = mapper.readValue(json, new TypeReference<List<Writer>>() {
        });
        // 输出[Writer(name=张三, age=18), Writer(name=李四, age=19)]
        System.out.println(writerList);
    }
}

4.日期格式

我们使用@JsonFormat注解实现自定义的日期格式

示例代码如下:

import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.*;

import java.util.Date;

/**
 * @author qinxun
 * @date 2023-06-09
 * @Descripion:
 */
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Writer {

    private String name;
    private int age;
    @JsonFormat(pattern = "yyyy年MM月dd日")
    private Date birthday;

}
import com.example.quartzdemo.bean.Writer;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Date;

/**
 * @author qinxun
 * @date 2023-06-09
 * @Descripion:
 */
@SpringBootTest
public class JacksonTest {

    @Test
    void test1() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        Writer writer = new Writer("张三", 25, new Date());
        String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(writer);
        System.out.println(json);
    }
}

程序执行:

{
  "name" : "张三",
  "age" : 25,
  "birthday" : "2023年06月09日"
}

5.字段过滤

在将 Java 对象序列化为 JSON 时,可能有些字段需要过滤,不显示在 JSON 中,我们使用@JsonIgnore 用于过滤单个字段。

示例代码如下:

import com.fasterxml.jackson.annotation.JsonFormat;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.*;

import java.util.Date;

/**
 * @author qinxun
 * @date 2023-06-09
 * @Descripion:
 */
@Getter
@Setter
@AllArgsConstructor
@NoArgsConstructor
@ToString
public class Writer {

    private String name;
    @JsonIgnore
    private int age;
    @JsonFormat(pattern = "yyyy年MM月dd日")
    private Date birthday;

}
import com.example.quartzdemo.bean.Writer;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;

import java.util.Date;

/**
 * @author qinxun
 * @date 2023-06-09
 * @Descripion:
 */
@SpringBootTest
public class JacksonTest {

    @Test
    void test1() throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        Writer writer = new Writer("张三", 25, new Date());
        String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(writer);
        System.out.println(json);
    }
}

程序执行结果

{
  "name" : "张三",
  "birthday" : "2023年06月09日"
}

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qinxun2008081/article/details/131124378

智能推荐

基于Kepler.gl 和 Google Earth Engine 卫星数据创建拉伸多边形地图-程序员宅基地

文章浏览阅读965次,点赞18次,收藏21次。现在我们有了 2021 年和 2023 年的 NDVI 数据帧,我们需要从 2021 年的值中减去 2023 年的值以捕获 NDVI 的差异。该数据集包括像素级别的植被值,我们将编写一个自定义函数来根据红色和绿色波段的表面反射率计算 NDVI。在我的上一篇文章中,我演示了如何将单个多边形分割/镶嵌为一组大小均匀的六边形。现在我们有了植被损失数据,让我们使用 Kepler.gl 可视化每个六边形的植被损失。将地图保存为 HTML 文件,在浏览器中打开 HTML 以获得更好的视图。现在我们将调用该函数并使用、

Echarts绘制任意数据的正态分布图_echarts正态分布图-程序员宅基地

文章浏览阅读3.3k次,点赞6次,收藏5次。正态分布,又称高斯分布或钟形曲线,是统计学中最为重要和常用的分布之一。_echarts正态分布图

Android中发送短信等普通方法_android bundle.get("pdus");-程序员宅基地

文章浏览阅读217次。首先要在Mainfest.xml中加入所需要的权限:[html] view plain copyprint?uses-permission android:name="android.permission.SEND_SMS"/> uses-permission android:name="android.permission.READ_SMS"/> _android bundle.get("pdus");

2021-07-26 WSL2 的安装和联网_wsl2 联网-程序员宅基地

文章浏览阅读2.6k次。0、说明最近在学习 Data Assimilation Research Testbed (DART) 相关内容,其软件是在 Unix/Linux 操作系统下编译和运行的 ,由于我的电脑是 Windows 10 的,DART 推荐可以使用 Windows Subsystem For Linux (WSL) 来创建一个 Windows 下的 Linux 子系统。以下的内容主要介绍如何安装 WSL2,以及 WSL2 的联网。1、如何在 Windows 10 下安装WSL具体的安装流程可以在 microso_wsl2 联网

DATABASE_LINK 数据库连接_添加 database link重复的数据库链接命-程序员宅基地

文章浏览阅读1k次。DB_LINK 介绍在本机数据库orcl上创建了一个prod_link的publicdblink(使用远程主机的scott用户连接),则用sqlplus连接到本机数据库,执行select * from scott.emp@prod_link即可以将远程数据库上的scott用户下的emp表中的数据获取到。也可以在本地建一个同义词来指向scott.emp@prod_link,这样取值就方便多了..._添加 database link重复的数据库链接命

云-腾讯云-实时音视频:实时音视频(TRTC)-程序员宅基地

文章浏览阅读3.1k次。ylbtech-云-腾讯云-实时音视频:实时音视频(TRTC)支持跨终端、全平台之间互通,从零开始快速搭建实时音视频通信平台1.返回顶部 1、腾讯实时音视频(Tencent Real-Time Communication,TRTC)拥有QQ十几年来在音视频技术上的积累,致力于帮助企业快速搭建低成本、高品质音视频通讯能力的完整解决方案。..._腾讯实时音视频 分享链接

随便推点

用c语言写个日历表_农历库c语言-程序员宅基地

文章浏览阅读534次,点赞10次,收藏8次。编写一个完整的日历表需要处理许多细节,包括公历和农历之间的转换、节气、闰年等。运行程序后,会输出指定年份的日历表。注意,这个程序只是一个简单的示例,还有很多可以改进和扩展的地方,例如添加节气、节日等。_农历库c语言

FL Studio21.1.1.3750中文破解百度网盘下载地址含Crack补丁_fl studio 21 注册机-程序员宅基地

文章浏览阅读1w次,点赞28次,收藏27次。FL Studio21.1.1.3750中文破解版是最优秀、最繁荣的数字音频工作站 (DAW) 之一,日新月异。它是一款录音机和编辑器,可让您不惜一切代价制作精美的音乐作品并保存精彩的活动画廊。为方便用户,FL Studio 21提供三种不同的版本——Fruity 版、Producer 版和签名版。所有这些版本都是独一无二的,同样具有竞争力。用户可以根据自己的需要选择其中任何一种。FL Studio21.1.1.3750中文版可以说是一站式综合音乐制作单位,可以让您录制、作曲、混音和编辑音乐。_fl studio 21 注册机

冯.诺伊曼体系结构的计算机工作原理是,冯 诺依曼型计算机的工作原理是什么...-程序员宅基地

文章浏览阅读1.3k次。冯诺依曼计算机工作原理冯 诺依曼计算机工作原理的核心是 和 程序控制世界上不同型号的计算机,就其工作原理而言,一般都是认为冯 诺依曼提出了什么原理冯 诺依曼原理中,计算机硬件系统由那五大部分组成的 急急急急急急急急急急急急急急急急急急急急急急冯诺依曼结构计算机工作原理的核心冯诺依曼结构和现代计算机结构模型 转载重学计算机组成原理 一 冯 诺依曼体系结构从冯.诺依曼的存储程序工作原理及计算机的组成来..._简述冯诺依曼计算机结构及工作原理

四国军棋引擎开发(2)简单的事件驱动模型下棋-程序员宅基地

文章浏览阅读559次。这次在随机乱下的基础上加上了一些简单的处理,如进营、炸棋、吃子等功能,在和敌方棋子产生碰撞之后会获取敌方棋子大小的一些信息,目前采用的是事件驱动模型,当下完一步棋界面返回结果后会判断是否触发了相关事件,有事件发生则处理相关事件,没有事件发生则仍然是随机下棋。1.事件驱动模型首先定义一个各种事件的枚举变量,目前的事件有工兵吃子,摸暗棋,进营,明确吃子,炸棋。定义如下:enum MoveE..._军棋引擎

STL与泛型编程-第一周笔记-Geekband-程序员宅基地

文章浏览阅读85次。1, 模板观念与函数模板简单模板: template< typename T > T Function( T a, T b) {… }类模板: template struct Object{……….}; 函数模板 template< class T> inline T Function( T a, T b){……} 不可以使用不同型别的..._geekband 讲义

vb.net正则表达式html,VB.Net常用的正则表达式(实例)-程序员宅基地

文章浏览阅读158次。"^\d+$"  //非负整数(正整数 + 0)"^[0-9]*[1-9][0-9]*$"  //正整数"^((-\d+)|(0+))$"  //非正整数(负整数 + 0)"^-[0-9]*[1-9][0-9]*$"  //负整数"^-?\d+$"    //整数"^\d+(\.\d+)?$"  //非负浮点数(正浮点数 + 0)"^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0..._vb.net 正则表达式 取html中的herf