首页 > 编程语言 >Java常用的几种JSON解析工具

Java常用的几种JSON解析工具

时间:2023-06-11 23:00:54浏览次数:39  
标签:序列化 Java name JSON studentId Student import 解析 com

一、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
}

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);
    }
}

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

如果字段的修饰符是 public,则该字段可序列化和反序列化(不是标准写法)。

如果字段的修饰符不是 public,但是它的 getter 方法和 setter 方法是 public,则该字段可序列化和反序列化。getter 方法用于序列化,setter 方法用于反序列化。

如果字段只有 public 的 setter 方法,而无 public 的 getter 方 法,则该字段只能用于反序列化。

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日"
}

返回的Json数据中没有发现age字段,成功过滤掉了这个字段。

标签:序列化,Java,name,JSON,studentId,Student,import,解析,com
From: https://blog.51cto.com/u_13312531/6459280

相关文章

  • java获取服务器ip地址的工具类
    参考:https://www.cnblogs.com/raphael5200/p/5996464.html代码实现importlombok.extern.slf4j.Slf4j;importjava.net.*;importjava.util.Enumeration;@Slf4jpublicclassIpUtil{publicstaticfinalStringDEFAULT_IP="127.0.0.1";/**......
  • java——微服务——spring cloud——Nacos——Nacos微服务配置拉取
       添加依赖:     添加bootstrap.yml文件    去除application.yml中和bootstrap.yaml中相同的配置项:      修改controller,验证配置更新功能            ......
  • Java11 Optional
    简介publicfinalclassOptional<T>{privatestaticfinalOptional<?>EMPTY=newOptional<>();privatefinalTvalue;privateOptional(){this.value=null;}……}Optional<T>是个容器,在java.util包中用......
  • Java反序列化之Commons-Collection篇04-CC4链
    <1>环境分析因为CommonsCollections4除4.0的其他版本去掉了InvokerTransformer不再继承Serializable,导致无法序列化。同时CommonsCollections4的版本TransformingComparator继承了Serializable接口,而CommonsCollections3里是没有的。这个就提供了一个攻击的路径jd......
  • IP地址解析DNS
    IP地址解析DNS背景指定IP解析域名,查看解析的域名,常用作CDN地址解析查询是否生效。本文章给出几个解决方案的shell脚本#!/bin/bash##****************************************************************************************#Author:wei#**************......
  • java——微服务——spring cloud——Nacos——Nacos实现配置管理
        注意:只填写需要修改的,不是把配置文件全部复制进去                      ......
  • Java用命令行给main方法传参
    Java用命令行给main方法传参1.cd到当前程序的src路径下。2.编译文件,我的文件是在com.test包下。javaccom/test/Demo.java3.给main方法传值。javacom/test/Demo.java123Dowhatyouthinkisright做你认为正确的事......
  • JavaSE笔记
    Markdown学习标题:二级标题三级标题四级标题字体粗体斜体斜体加粗删除线引用学习markdown分割线图片超链接陈伟强的博客列表abcabc表格名字性别生日陈伟强男2002代码publicwindows常用快捷键ctrl+C:复制ctrl+V:粘贴ctrl+A:全......
  • Java包装类
    包装类 其实就是其实就是8种基本数据类型对应的引用类型。 为什么提供包装类?1、java为了实现一切皆对象,为8种基本类型提供了对应的引用类型2、后面的集合和泛型其实也只能支持包装类型,不支持基本数据类型自动装箱:基本类型的数据和变量可以直接赋值给包装类型的变量。自......
  • 【技术积累】Java中的泛型【一】
    泛型是什么Java中的泛型是一种能够让用户在编写代码时避免使用明确的类型而进行类型参数化的机制。Java中的泛型可以让编程者在代码编写时不必关心具体类型,只用关心类型之间的关系和相互转换,从而在编写代码的过程中实现类型的复用。这使得代码更加简洁、可读性更高,并且可以提高代......