Java常用的几种JSON解析工具

这篇具有很好参考价值的文章主要介绍了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);
    }
}

程序执行结果文章来源地址https://www.toymoban.com/news/detail-488050.html

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

到了这里,关于Java常用的几种JSON解析工具的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • 华为手机配置google play的几种方式

    介绍几种常见的方式 1、华为自带的谷歌商店,通过手机设置开启 。具体步骤如下: 1、进入华为手机设置界面,找到Googel, 2、点击Google,进入设置界面,点击解除即打开Google Play服务, Google Play 前名为Android Market,是一个由Google为Android设备开发的在线 华为自带的谷歌商店 2、在第三

    2024年02月11日
    浏览(38)
  • 常用的将Java的String字符串转具体对象的几种方式

    Java对象以User.class为例 ,注意:代码中使用到了lombok的@Data注解 以上就是常用的几种String转具体的java对象操作

    2024年04月11日
    浏览(36)
  • 推荐Java开发常用的工具类库google guava

    Guava Guava是一个Google开源的Java核心库,它提供了许多实用的工具和辅助类,使Java开发更加简洁、高效、可靠。目前和 hutool 一起,是业界常用的工具类库。 shigen 也比较喜欢使用,在这里列举一下常用的工具类库和使用的案例。 参考: 整理一波Guava的使用技巧 - 掘金 Guava中这

    2024年02月09日
    浏览(34)
  • Unity读取Json的几种方法

    目录 存入和读取JSON工具 读取本地Json文件 1、unity自带方法 类名:JsonUtility          序列化:ToJson()                    反序列化:FromJson()         用于接收的JSON实体类需要声明 [Serializable]  序列化 实体类中的成员变量要是字段而不是属性{get;set;} 处理数组的话,外

    2024年01月21日
    浏览(29)
  • 【JAVA】各JSON工具对比及常用转换

    工具名称 使用 场景 Gson 需要先建好对象的类型及成员才能转换 数据量少,javabean-json *FastJson 复杂的Bean转换Json会有问题 数据量少,字符串-》json Jackson 转换的json不是标准json 数据量大,不能对对象集合解析,只能转成一个Map,字符串-》json,javabean-json Json-lib 不能满足互联网需

    2024年02月16日
    浏览(28)
  • fastjson json字符串转map的几种方法

    参考:fastjson将json字符串转化成map的五种方法 - 何其小静 - 博客园 (cnblogs.com) 源码: 第一种 Map maps = (Map)JSON.parse(str); 第二种 Map mapTypes = JSON.parseObject(str); JSONObject实现了Map,所以可以用Map接收 

    2024年02月16日
    浏览(33)
  • java hutool工具类处理json的常用方法

    Hutool 提供了丰富的 JSON 处理工具类,包括 JSON 字符串的解析、生成、对象与 JSON 字符串的转换等。以下是 Hutool 中关于 JSON 的常用方法: JSON 字符串的解析与生成: JSONUtil.parseObj(jsonStr) :将 JSON 字符串解析为 JSONObject 对象。 JSONUtil.parseArray(jsonStr) :将 JSON 字符串解析为 JSON

    2024年04月17日
    浏览(35)
  • 【开源与项目实战:开源实战】82 | 开源实战三(中):剖析Google Guava中用到的几种设计模式

    上一节课,我们通过 Google Guava 这样一个优秀的开源类库,讲解了如何在业务开发中,发现跟业务无关、可以复用的通用功能模块,并将它们从业务代码中抽离出来,设计开发成独立的类库、框架或功能组件。 今天,我们再来学习一下,Google Guava 中用到的几种经典设计模式:

    2024年02月11日
    浏览(53)
  • 【JavaScript】 发送 POST 请求并带有 JSON 请求体的几种方法

     在现代的前端开发中,与后端进行数据交互是必不可少的。其中,发送 POST 请求并带有 JSON 请求体是一种常见的需求。在本文中,我们将介绍在 JavaScript 中实现这一需求的几种方法。   XMLHttpRequest 是一种传统的发送网络请求的方式。以下是一个使用 XMLHttpRequest 发送 POST 请

    2024年03月19日
    浏览(46)
  • shell 简单且常用的几种

    目录 一、配置环境的shell脚本  二、系统资源脚本 一、要求 二、脚本内容 三、脚本解析 四、赋权并验证 三、查看当前内存的总大小、实际使用大小、剩余大小、显示使用率百分比的脚本 一、第一种方法 二、验证 三、第二种方法 四、验证 四、查看网卡实时流量脚本 一、

    2024年02月12日
    浏览(33)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包