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

智能推荐

EasyDarwin开源流媒体云平台之EasyRMS录播服务器功能设计_开源录播系统-程序员宅基地

文章浏览阅读3.6k次。需求背景EasyDarwin开发团队维护EasyDarwin开源流媒体服务器也已经很多年了,之前也陆陆续续尝试过很多种服务端录像的方案,有:在EasyDarwin中直接解析收到的RTP包,重新组包录像;也有:在EasyDarwin中新增一个RecordModule,再以RTSPClient的方式请求127.0.0.1自己的直播流录像,但这些始终都没有成气候;我们的想法是能够让整套EasyDarwin_开源录播系统

oracle Plsql 执行update或者delete时卡死问题解决办法_oracle delete update 锁表问题-程序员宅基地

文章浏览阅读1.1w次。今天碰到一个执行语句等了半天没有执行:delete table XXX where ......,但是在select 的时候没问题。后来发现是在执行select * from XXX for update 的时候没有commit,oracle将该记录锁住了。可以通过以下办法解决: 先查询锁定记录 Sql代码 SELECT s.sid, s.seri_oracle delete update 锁表问题

Xcode Undefined symbols 错误_xcode undefined symbols:-程序员宅基地

文章浏览阅读3.4k次。报错信息error:Undefined symbol: typeinfo for sdk::IConfigUndefined symbol: vtable for sdk::IConfig具体信息:Undefined symbols for architecture x86_64: "typeinfo for sdk::IConfig", referenced from: typeinfo for sdk::ConfigImpl in sdk.a(config_impl.o) _xcode undefined symbols:

项目05(Mysql升级07Mysql5.7.32升级到Mysql8.0.22)_mysql8.0.26 升级32-程序员宅基地

文章浏览阅读249次。背景《承接上文,项目05(Mysql升级06Mysql5.6.51升级到Mysql5.7.32)》,写在前面需要(考虑)检查和测试的层面很多,不限于以下内容。参考文档https://dev.mysql.com/doc/refman/8.0/en/upgrade-prerequisites.htmllink推荐阅读以上链接,因为对应以下问题,有详细的建议。官方文档:不得存在以下问题:0.不得有使用过时数据类型或功能的表。不支持就地升级到MySQL 8.0,如果表包含在预5.6.4格_mysql8.0.26 升级32

高通编译8155源码环境搭建_高通8155 qnx 源码-程序员宅基地

文章浏览阅读3.7k次。一.安装基本环境工具:1.安装git工具sudo apt install wget g++ git2.检查并安装java等环境工具2.1、执行下面安装命令#!/bin/bashsudoapt-get-yinstall--upgraderarunrarsudoapt-get-yinstall--upgradepython-pippython3-pip#aliyunsudoapt-get-yinstall--upgradeopenjdk..._高通8155 qnx 源码

firebase 与谷歌_Firebase的好与不好-程序员宅基地

文章浏览阅读461次。firebase 与谷歌 大多数开发人员都听说过Google的Firebase产品。 这就是Google所说的“ 移动平台,可帮助您快速开发高质量的应用程序并发展业务。 ”。 它基本上是大多数开发人员在构建应用程序时所需的一组工具。 在本文中,我将介绍这些工具,并指出您选择使用Firebase时需要了解的所有内容。 在开始之前,我需要说的是,我不会详细介绍Firebase提供的所有工具。 我..._firsebase 与 google

随便推点

k8s挂载目录_kubernetes(k8s)的pod使用统一的配置文件configmap挂载-程序员宅基地

文章浏览阅读1.2k次。在容器化应用中,每个环境都要独立的打一个镜像再给镜像一个特有的tag,这很麻烦,这就要用到k8s原生的配置中心configMap就是用解决这个问题的。使用configMap部署应用。这里使用nginx来做示例,简单粗暴。直接用vim常见nginx的配置文件,用命令导入进去kubectl create cm nginx.conf --from-file=/home/nginx.conf然后查看kub..._pod mount目录会自动创建吗

java计算机毕业设计springcloud+vue基于微服务的分布式新生报到系统_关于spring cloud的参考文献有啥-程序员宅基地

文章浏览阅读169次。随着互联网技术的发发展,计算机技术广泛应用在人们的生活中,逐渐成为日常工作、生活不可或缺的工具,高校各种管理系统层出不穷。高校作为学习知识和技术的高等学府,信息技术更加的成熟,为新生报到管理开发必要的系统,能够有效的提升管理效率。一直以来,新生报到一直没有进行系统化的管理,学生无法准确查询学院信息,高校也无法记录新生报名情况,由此提出开发基于微服务的分布式新生报到系统,管理报名信息,学生可以在线查询报名状态,节省时间,提高效率。_关于spring cloud的参考文献有啥

VB.net学习笔记(十五)继承与多接口练习_vb.net 继承多个接口-程序员宅基地

文章浏览阅读3.2k次。Public MustInherit Class Contact '只能作基类且不能实例化 Private mID As Guid = Guid.NewGuid Private mName As String Public Property ID() As Guid Get Return mID End Get_vb.net 继承多个接口

【Nexus3】使用-Nexus3批量上传jar包 artifact upload_nexus3 批量上传jar包 java代码-程序员宅基地

文章浏览阅读1.7k次。1.美图# 2.概述因为要上传我的所有仓库的包,希望nexus中已有的包,我不覆盖,没有的添加。所以想批量上传jar。3.方案1-脚本批量上传PS:nexus3.x版本只能通过脚本上传3.1 批量放入jar在mac目录下,新建一个文件夹repo,批量放入我们需要的本地库文件夹,并对文件夹授权(base) lcc@lcc nexus-3.22.0-02$ mkdir repo2..._nexus3 批量上传jar包 java代码

关于去隔行的一些概念_mipi去隔行-程序员宅基地

文章浏览阅读6.6k次,点赞6次,收藏30次。本文转自http://blog.csdn.net/charleslei/article/details/486519531、什么是场在介绍Deinterlacer去隔行处理的方法之前,我们有必要提一下关于交错场和去隔行处理的基本知识。那么什么是场呢,场存在于隔行扫描记录的视频中,隔行扫描视频的每帧画面均包含两个场,每一个场又分别含有该帧画面的奇数行扫描线或偶数行扫描线信息,_mipi去隔行

ABAP自定义Search help_abap 自定义 search help-程序员宅基地

文章浏览阅读1.7k次。DATA L_ENDDA TYPE SY-DATUM. IF P_DATE IS INITIAL. CONCATENATE SY-DATUM(4) '1231' INTO L_ENDDA. ELSE. CONCATENATE P_DATE(4) '1231' INTO L_ENDDA. ENDIF. DATA: LV_RESET(1) TY_abap 自定义 search help