国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

Java常用的幾種JSON解析工具

這篇具有很好參考價值的文章主要介紹了Java常用的幾種JSON解析工具。希望對大家有所幫助。如果存在錯誤或未考慮完全的地方,請大家不吝賜教,您也可以點(diǎn)擊"舉報違法"按鈕提交疑問。

一、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:用于序列化,對象轉(zhuǎn)Json數(shù)據(jù)
fromJson:用于反序列化,把Json數(shù)據(jù)轉(zhuǎn)成對象

示例代碼如下:

import lombok.*;

/**
 * @author qinxun
 * @date 2023-05-30
 * @Descripion: 學(xué)生實(shí)體類
 */
@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):用于序列化對象,轉(zhuǎn)成json數(shù)據(jù)。

JSON.parseObject(obj,class): 用于反序列化對象,轉(zhuǎn)成數(shù)據(jù)對象。

JSON.parseArray():把 JSON 字符串轉(zhuǎn)成集合

示例代碼如下:

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 對象中的字段不匹配,比如大小寫;有時候,你需要指定一些字段序列化但不反序列化;有時候,你需要日期字段顯示成指定的格式。

我們只需要在對應(yīng)的字段上加上?@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: 學(xué)生實(shí)體類
 */
@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;

}

我們設(shè)置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);
    }
}

執(zhí)行結(jié)果:

{"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)]

我們發(fā)現(xiàn)studentId沒有被序列化成json數(shù)據(jù)。birthday生成了自定義的數(shù)據(jù)格式。

三、Jackson:SpringBoot默認(rèn)的JSON解析工具

1.添加依賴

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

我們添加默認(rèn)的web依賴就自動的添加了Jackson的依賴。

2.序列化

  • writeValueAsString(Object value)?方法,將對象存儲成字符串
  • writeValueAsBytes(Object value)?方法,將對象存儲成字節(jié)數(shù)組
  • 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);
    }
}

執(zhí)行結(jié)果:

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

不是所有的字段都支持序列化和反序列化,需要符合以下規(guī)則:

  • 如果字段的修飾符是 public,則該字段可序列化和反序列化(不是標(biāo)準(zhǔn)寫法)。
  • 如果字段的修飾符不是 public,但是它的 getter 方法和 setter 方法是 public,則該字段可序列化和反序列化。getter 方法用于序列化,setter 方法用于反序列化。
  • 如果字段只有 public 的 setter 方法,而無 public 的 getter 方 法,則該字段只能用于反序列化。

3.反序列化

  • readValue(String content, Class<T> valueType)?方法,將字符串反序列化為 Java 對象
  • readValue(byte[] src, Class<T> valueType)?方法,將字節(jié)數(shù)組反序列化為 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 字符串?dāng)?shù)組轉(zhuǎn)成泛型 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注解實(shí)現(xiàn)自定義的日期格式

示例代碼如下:

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

程序執(zhí)行:

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

程序執(zhí)行結(jié)果文章來源地址http://www.zghlxwxcb.cn/news/detail-488050.html

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

到了這里,關(guān)于Java常用的幾種JSON解析工具的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請點(diǎn)擊違法舉報進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

  • 華為手機(jī)配置google play的幾種方式

    介紹幾種常見的方式 1、華為自帶的谷歌商店,通過手機(jī)設(shè)置開啟 。具體步驟如下: 1、進(jìn)入華為手機(jī)設(shè)置界面,找到Googel, 2、點(diǎn)擊Google,進(jìn)入設(shè)置界面,點(diǎn)擊解除即打開Google Play服務(wù), Google Play 前名為Android Market,是一個由Google為Android設(shè)備開發(fā)的在線 華為自帶的谷歌商店 2、在第三

    2024年02月11日
    瀏覽(25)
  • 常用的將Java的String字符串轉(zhuǎn)具體對象的幾種方式

    常用的將Java的String字符串轉(zhuǎn)具體對象的幾種方式

    Java對象以User.class為例 ,注意:代碼中使用到了lombok的@Data注解 以上就是常用的幾種String轉(zhuǎn)具體的java對象操作

    2024年04月11日
    瀏覽(40)
  • 推薦Java開發(fā)常用的工具類庫google guava

    Guava Guava是一個Google開源的Java核心庫,它提供了許多實(shí)用的工具和輔助類,使Java開發(fā)更加簡潔、高效、可靠。目前和 hutool 一起,是業(yè)界常用的工具類庫。 shigen 也比較喜歡使用,在這里列舉一下常用的工具類庫和使用的案例。 參考: 整理一波Guava的使用技巧 - 掘金 Guava中這

    2024年02月09日
    瀏覽(24)
  • Unity讀取Json的幾種方法

    目錄 存入和讀取JSON工具 讀取本地Json文件 1、unity自帶方法 類名:JsonUtility? ? ? ? ? 序列化:ToJson()? ? ? ? ? ? ? ? ? ? 反序列化:FromJson()???????? 用于接收的JSON實(shí)體類需要聲明 [Serializable] ?序列化 實(shí)體類中的成員變量要是字段而不是屬性{get;set;} 處理數(shù)組的話,外

    2024年01月21日
    瀏覽(20)
  • 【JAVA】各JSON工具對比及常用轉(zhuǎn)換

    工具名稱 使用 場景 Gson 需要先建好對象的類型及成員才能轉(zhuǎn)換 數(shù)據(jù)量少,javabean-json *FastJson 復(fù)雜的Bean轉(zhuǎn)換Json會有問題 數(shù)據(jù)量少,字符串-》json Jackson 轉(zhuǎn)換的json不是標(biāo)準(zhǔn)json 數(shù)據(jù)量大,不能對對象集合解析,只能轉(zhuǎn)成一個Map,字符串-》json,javabean-json Json-lib 不能滿足互聯(lián)網(wǎng)需

    2024年02月16日
    瀏覽(17)
  • fastjson json字符串轉(zhuǎn)map的幾種方法

    參考:fastjson將json字符串轉(zhuǎn)化成map的五種方法 - 何其小靜 - 博客園 (cnblogs.com) 源碼: 第一種 Map maps = (Map)JSON.parse(str); 第二種 Map mapTypes = JSON.parseObject(str); JSONObject實(shí)現(xiàn)了Map,所以可以用Map接收?

    2024年02月16日
    瀏覽(20)
  • java hutool工具類處理json的常用方法

    Hutool 提供了豐富的 JSON 處理工具類,包括 JSON 字符串的解析、生成、對象與 JSON 字符串的轉(zhuǎn)換等。以下是 Hutool 中關(guān)于 JSON 的常用方法: JSON 字符串的解析與生成: JSONUtil.parseObj(jsonStr) :將 JSON 字符串解析為 JSONObject 對象。 JSONUtil.parseArray(jsonStr) :將 JSON 字符串解析為 JSON

    2024年04月17日
    瀏覽(18)
  • 【開源與項目實(shí)戰(zhàn):開源實(shí)戰(zhàn)】82 | 開源實(shí)戰(zhàn)三(中):剖析Google Guava中用到的幾種設(shè)計模式

    【開源與項目實(shí)戰(zhàn):開源實(shí)戰(zhàn)】82 | 開源實(shí)戰(zhàn)三(中):剖析Google Guava中用到的幾種設(shè)計模式

    上一節(jié)課,我們通過 Google Guava 這樣一個優(yōu)秀的開源類庫,講解了如何在業(yè)務(wù)開發(fā)中,發(fā)現(xiàn)跟業(yè)務(wù)無關(guān)、可以復(fù)用的通用功能模塊,并將它們從業(yè)務(wù)代碼中抽離出來,設(shè)計開發(fā)成獨(dú)立的類庫、框架或功能組件。 今天,我們再來學(xué)習(xí)一下,Google Guava 中用到的幾種經(jīng)典設(shè)計模式:

    2024年02月11日
    瀏覽(38)
  • 【JavaScript】 發(fā)送 POST 請求并帶有 JSON 請求體的幾種方法

    ?在現(xiàn)代的前端開發(fā)中,與后端進(jìn)行數(shù)據(jù)交互是必不可少的。其中,發(fā)送 POST 請求并帶有 JSON 請求體是一種常見的需求。在本文中,我們將介紹在 JavaScript 中實(shí)現(xiàn)這一需求的幾種方法。 ? XMLHttpRequest 是一種傳統(tǒng)的發(fā)送網(wǎng)絡(luò)請求的方式。以下是一個使用 XMLHttpRequest 發(fā)送 POST 請

    2024年03月19日
    瀏覽(27)
  • shell 簡單且常用的幾種

    shell 簡單且常用的幾種

    目錄 一、配置環(huán)境的shell腳本 ?二、系統(tǒng)資源腳本 一、要求 二、腳本內(nèi)容 三、腳本解析 四、賦權(quán)并驗(yàn)證 三、查看當(dāng)前內(nèi)存的總大小、實(shí)際使用大小、剩余大小、顯示使用率百分比的腳本 一、第一種方法 二、驗(yàn)證 三、第二種方法 四、驗(yàn)證 四、查看網(wǎng)卡實(shí)時流量腳本 一、

    2024年02月12日
    瀏覽(19)

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包