Gson 代码示例

不管现实多么惨不忍睹,都要持之以恒地相信,这只是黎明前短暂的黑暗而已。不要惶恐眼前的难关迈不过去,不要担心此刻的付出没有回报,别再花时间等待天降好运。真诚做人,努力做事!你想要的,岁月都会给你。Gson 代码示例,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com,来源:原文

Gson 代码示例

示例代码中包含 Date LocalDate LocalDateTime 类型处理方式
JavaBean 与 json 相互转换 bean2json json2bean
List 与 json 相互转换 list2json json2list
Map 与 json 相互转换map2json json2map

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>com.lihaohze</groupId>
    <artifactId>chap06</artifactId>
    <version>1.0.0</version>
    <packaging>jar</packaging>
    <name>chap06</name>
    <url>https://mvnrepository.com/</url>

    <properties>
        <!-- 公共配置 -->
        <maven.compiler.source>21</maven.compiler.source>
        <maven.compiler.target>21</maven.compiler.target>
        <maven.compiler.compilerVersion>21</maven.compiler.compilerVersion>
        <maven.compiler.encoding>utf-8</maven.compiler.encoding>
        <project.build.sourceEncoding>utf-8</project.build.sourceEncoding>
        <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
        <maven.test.failure.ignore>true</maven.test.failure.ignore>
        <maven.test.skip>true</maven.test.skip>

        <commons-io.version>2.14.0</commons-io.version>
        <commons-lang3.version>3.13.0</commons-lang3.version>
        <hutool.version>5.8.22</hutool.version>
        <junit.version>5.10.0</junit.version>
        <lombok.version>1.18.30</lombok.version>
    </properties>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-api -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-api</artifactId>
            <version>${junit.version}</version>
            <!-- 作用域 -->
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.junit.jupiter/junit-jupiter-engine -->
        <dependency>
            <groupId>org.junit.jupiter</groupId>
            <artifactId>junit-jupiter-engine</artifactId>
            <version>${junit.version}</version>
            <scope>test</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>${lombok.version}</version>
            <scope>provided</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/cn.hutool/hutool-all -->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>${hutool.version}</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>${commons-lang3.version}</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>${commons-io.version}</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson -->
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.10.1</version>
        </dependency>
    </dependencies>
</project>

javabean与json格式字符串相互转换

准备javabean

package com.lihaozhe.json.gson;

import com.google.gson.annotations.JsonAdapter;
import com.lihaozhe.util.date.DateUtils;
import com.lihaozhe.util.json.gson.DateAdapter;
import com.lihaozhe.util.json.gson.LocalDateAdapter;
import com.lihaozhe.util.json.gson.LocalDateTimeAdapter;
import lombok.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @author 李昊哲
 * @version 1.0
 * @create 2023/10/19
 */
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Emp {
    /**
     * 账号
     */
    private String account;
    /**
     * 密码
     */
    private String password;
    /**
     * 姓名
     */
    private String name;
    /**
     * 性别 1 代表男性 0 代表女性
     */
    private int gender;

}

javabean转json格式字符串

Emp emp = new Emp("admin", "e10adc3949ba59abbe56e057f20f883e", "李昊哲", 1);
System.out.println(emp);
Gson gson = new Gson();
String json = gson.toJson(emp);
System.out.println(json);

结果如下:

Emp(account=admin, password=e10adc3949ba59abbe56e057f20f883e, name=李昊哲, gender=1)
{"account":"admin","password":"e10adc3949ba59abbe56e057f20f883e","name":"李昊哲","gender":1}

json格式字符串转javabean

Emp emp = new Emp("admin", "e10adc3949ba59abbe56e057f20f883e", "李昊哲", 1);
System.out.println(emp);
Gson gson = new Gson();
String json = gson.toJson(emp);
System.out.println(json);
Emp fromJson = gson.fromJson(json, Emp.class);
System.out.println(fromJson);

结果如下:

Emp(account=admin, password=e10adc3949ba59abbe56e057f20f883e, name=李昊哲, gender=1)
{"account":"admin","password":"e10adc3949ba59abbe56e057f20f883e","name":"李昊哲","gender":1}
Emp(account=admin, password=e10adc3949ba59abbe56e057f20f883e, name=李昊哲, gender=1)

Gson 处理 Date 类型

准备javabean

package com.lihaozhe.json.gson;

import com.google.gson.annotations.JsonAdapter;
import com.lihaozhe.util.date.DateUtils;
import com.lihaozhe.util.json.gson.DateAdapter;
import com.lihaozhe.util.json.gson.LocalDateAdapter;
import com.lihaozhe.util.json.gson.LocalDateTimeAdapter;
import lombok.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @author 李昊哲
 * @version 1.0
 * @create 2023/10/19
 */
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Emp {
    /**
     * 账号
     */
    private String account;
    /**
     * 密码
     */
    private String password;
    /**
     * 姓名
     */
    private String name;
    /**
     * 性别 1 代表男性 0 代表女性
     */
    private int gender;
    /**
     * 入职时间
     */
    @JsonAdapter(DateAdapter.class)
    private Date hiredate;
    /**
     * 离职日期
     */
    @JsonAdapter(DateAdapter.class)
    private Date turnoverDate;
    
    public Emp(String account, String password, String name, int gender) {
        this.account = account;
        this.password = password;
        this.name = name;
        this.gender = gender;
        this.hiredate = new Date();
    }

}

javabean转json格式字符串

Emp emp = new Emp("admin", "e10adc3949ba59abbe56e057f20f883e", "李昊哲", 1);
System.out.println(emp);
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
String json = gson.toJson(emp);
System.out.println(json);

结果如下:

Emp(account=admin, password=e10adc3949ba59abbe56e057f20f883e, name=李昊哲, gender=1, hiredate=Thu Oct 19 19:10:18 CST 2023, turnoverDate=null,)
{"account":"admin","password":"e10adc3949ba59abbe56e057f20f883e","name":"李昊哲","gender":1,"hiredate":"2023-10-19 19:10:18"}

json格式字符串转javabean

Emp emp = new Emp("admin", "e10adc3949ba59abbe56e057f20f883e", "李昊哲", 1);
System.out.println(emp);
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
String json = gson.toJson(emp);
System.out.println(json);
Emp fromJson = gson.fromJson(json, Emp.class);
System.out.println(fromJson);
        

结果如下:

Emp(account=admin, password=e10adc3949ba59abbe56e057f20f883e, name=李昊哲, gender=1, hiredate=Thu Oct 19 19:10:18 CST 2023, turnoverDate=null)
{"account":"admin","password":"e10adc3949ba59abbe56e057f20f883e","name":"李昊哲","gender":1,"hiredate":"2023-10-19 19:10:18"}
Emp(account=admin, password=e10adc3949ba59abbe56e057f20f883e, name=李昊哲, gender=1, hiredate=Thu Oct 19 19:10:18 CST 2023, turnoverDate=null)

Gson 注解方式处理 Date LocalDate LocalDateTime

准备 DateAdapter

package com.lihaozhe.util.json.gson;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * @author 李昊哲
 * @version 1.0
 * @create 2023/10/19
 */
public class DateAdapter implements JsonDeserializer<Date>, JsonSerializer<Date> {
    private final DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(dateFormat.format(src));
    }

    @Override
    public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        try {
            return dateFormat.parse(json.getAsString());
        } catch (Exception e) {
            throw new JsonParseException(e);
        }
    }
}

准备 LocalDateAdapter

package com.lihaozhe.util.json.gson;

/**
 * @author 李昊哲
 * @version 1.0
 * @create 2023/10/19
 */

import com.google.gson.*;

import java.lang.reflect.Type;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

public class LocalDateAdapter implements JsonDeserializer<LocalDate>, JsonSerializer<LocalDate> {
    private final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");

    @Override
    public JsonElement serialize(LocalDate src, Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(dateTimeFormatter.format(src));
    }

    @Override
    public LocalDate deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        try {
            return LocalDate.parse(json.getAsString(), dateTimeFormatter);
        } catch (Exception e) {
            throw new JsonParseException(e);
        }
    }
}

准备 LocalDateTimeAdapter

package com.lihaozhe.util.json.gson;

import com.google.gson.*;

import java.lang.reflect.Type;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author 李昊哲
 * @version 1.0
 * @create 2023/10/19
 */
public class LocalDateTimeAdapter implements JsonDeserializer<LocalDateTime>, JsonSerializer<LocalDateTime> {
    private final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    @Override
    public JsonElement serialize(LocalDateTime src, Type typeOfSrc, JsonSerializationContext context) {
        return new JsonPrimitive(dateTimeFormatter.format(src));
    }

    @Override
    public LocalDateTime deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException {
        try {
            return LocalDateTime.parse(json.getAsString(), dateTimeFormatter);
        } catch (Exception e) {
            throw new JsonParseException(e);
        }
    }
}

准备javabean

package com.lihaozhe.json.gson;

import com.google.gson.annotations.JsonAdapter;
import com.lihaozhe.util.date.DateUtils;
import com.lihaozhe.util.json.gson.DateAdapter;
import com.lihaozhe.util.json.gson.LocalDateAdapter;
import com.lihaozhe.util.json.gson.LocalDateTimeAdapter;
import lombok.*;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Date;

/**
 * @author 李昊哲
 * @version 1.0
 * @create 2023/10/19
 */
@Getter
@Setter
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class Emp {
    /**
     * 账号
     */
    private String account;
    /**
     * 密码
     */
    private String password;
    /**
     * 姓名
     */
    private String name;
    /**
     * 性别 1 代表男性 0 代表女性
     */
    private int gender;

    /**
     * 入职时间
     */
    @JsonAdapter(DateAdapter.class)
    private Date hiredate;
    /**
     * 离职日期
     */
    @JsonAdapter(DateAdapter.class)
    private Date turnoverDate;
    /**
     * 账号注册日期
     */
    @JsonAdapter(LocalDateAdapter.class)
    private LocalDate createDate;
    /**
     * 账号注册日期时间
     */
    @JsonAdapter(LocalDateTimeAdapter.class)
    private LocalDateTime createDateTime;

    public Emp(String account, String password, String name, int gender) {
        this.account = account;
        this.password = password;
        this.name = name;
        this.gender = gender;
        this.hiredate = new Date();
        this.createDate = LocalDate.now();
        this.createDateTime = LocalDateTime.now();
    }
}

javabean转json格式字符串

Emp emp = new Emp("admin", "e10adc3949ba59abbe56e057f20f883e", "李昊哲", 1);
System.out.println(emp);
Gson gson = new Gson();
String json = gson.toJson(emp);
System.out.println(json);

结果如下:

Emp(account=admin, password=e10adc3949ba59abbe56e057f20f883e, name=李昊哲, gender=1, hiredate=Thu Oct 19 19:20:29 CST 2023, turnoverDate=null, createDate=2023-10-19, createDateTime=2023-10-19T19:20:29.118)
{"account":"admin","password":"e10adc3949ba59abbe56e057f20f883e","name":"李昊哲","gender":1,"hiredate":"2023-10-19 19:20:29","createDate":"2023-10-19","createDateTime":"2023-10-19 19:20:29"}

json格式字符串转javabean

Emp emp = new Emp("admin", "e10adc3949ba59abbe56e057f20f883e", "李昊哲", 1);
System.out.println(emp);
Gson gson = new Gson();
String json = gson.toJson(emp);
System.out.println(json);
Emp fromJson = gson.fromJson(json, Emp.class);
System.out.println(fromJson);
        

结果如下:

Emp(account=admin, password=e10adc3949ba59abbe56e057f20f883e, name=李昊哲, gender=1, hiredate=Thu Oct 19 19:20:29 CST 2023, turnoverDate=null, createDate=2023-10-19, createDateTime=2023-10-19T19:20:29.118)
{"account":"admin","password":"e10adc3949ba59abbe56e057f20f883e","name":"李昊哲","gender":1,"hiredate":"2023-10-19 19:20:29","createDate":"2023-10-19","createDateTime":"2023-10-19 19:20:29"}
Emp(account=admin, password=e10adc3949ba59abbe56e057f20f883e, name=李昊哲, gender=1, hiredate=Thu Oct 19 19:20:29 CST 2023, turnoverDate=null, createDate=2023-10-19, createDateTime=2023-10-19T19:20:29.118)

list与json格式字符串相互转换

list转json格式字符串

List<Emp> empList = new ArrayList<>();
empList.add(new Emp("root", "e10adc3949ba59abbe56e057f20f883e", "李昊哲", 1));
empList.add(new Emp("admin", "e10adc3949ba59abbe56e057f20f883e", "李哲", 0));
empList.forEach(System.out::println);
Gson gson = new Gson();
String json = gson.toJson(empList);
System.out.println(json);

结果如下:

Emp(account=root, password=e10adc3949ba59abbe56e057f20f883e, name=李昊哲, gender=1, hiredate=Thu Oct 19 19:23:08 CST 2023, turnoverDate=null, createDate=2023-10-19, createDateTime=2023-10-19T19:23:08.606)
Emp(account=admin, password=e10adc3949ba59abbe56e057f20f883e, name=李哲, gender=0, hiredate=Thu Oct 19 19:23:08 CST 2023, turnoverDate=null, createDate=2023-10-19, createDateTime=2023-10-19T19:23:08.609)
[{"account":"root","password":"e10adc3949ba59abbe56e057f20f883e","name":"李昊哲","gender":1,"hiredate":"2023-10-19 19:23:08","createDate":"2023-10-19","createDateTime":"2023-10-19 19:23:08"},{"account":"admin","password":"e10adc3949ba59abbe56e057f20f883e","name":"李哲","gender":0,"hiredate":"2023-10-19 19:23:08","createDate":"2023-10-19","createDateTime":"2023-10-19 19:23:08"}]

json格式字符串转list

List<Emp> empList = new ArrayList<>();
empList.add(new Emp("root", "e10adc3949ba59abbe56e057f20f883e", "李昊哲", 1));
empList.add(new Emp("admin", "e10adc3949ba59abbe56e057f20f883e", "李哲", 0));
empList.forEach(System.out::println);
Gson gson = new Gson();
String json = gson.toJson(empList);
System.out.println(json);
List<Emp> emps = gson.fromJson(json, new TypeToken<>() {
});
emps.forEach(System.out::println);

结果如下:

Emp(account=root, password=e10adc3949ba59abbe56e057f20f883e, name=李昊哲, gender=1, hiredate=Thu Oct 19 19:23:08 CST 2023, turnoverDate=null, createDate=2023-10-19, createDateTime=2023-10-19T19:23:08.606)
Emp(account=admin, password=e10adc3949ba59abbe56e057f20f883e, name=李哲, gender=0, hiredate=Thu Oct 19 19:23:08 CST 2023, turnoverDate=null, createDate=2023-10-19, createDateTime=2023-10-19T19:23:08.609)
[{"account":"root","password":"e10adc3949ba59abbe56e057f20f883e","name":"李昊哲","gender":1,"hiredate":"2023-10-19 19:23:08","createDate":"2023-10-19","createDateTime":"2023-10-19 19:23:08"},{"account":"admin","password":"e10adc3949ba59abbe56e057f20f883e","name":"李哲","gender":0,"hiredate":"2023-10-19 19:23:08","createDate":"2023-10-19","createDateTime":"2023-10-19 19:23:08"}]
Emp(account=root, password=e10adc3949ba59abbe56e057f20f883e, name=李昊哲, gender=1, hiredate=Thu Oct 19 19:23:08 CST 2023, turnoverDate=null, createDate=2023-10-19, createDateTime=2023-10-19T19:23:08.606)
Emp(account=admin, password=e10adc3949ba59abbe56e057f20f883e, name=李哲, gender=0, hiredate=Thu Oct 19 19:23:08 CST 2023, turnoverDate=null, createDate=2023-10-19, createDateTime=2023-10-19T19:23:08.609)

map与json格式字符串相互转换

map转json格式字符串

Map<String, Emp> map = new HashMap<>();
map.put("root", new Emp("root", "e10adc3949ba59abbe56e057f20f883e", "李昊哲", 1));
map.put("admin", new Emp("admin", "e10adc3949ba59abbe56e057f20f883e", "李哲", 0));
map.forEach((key, value) -> System.out.println("key >>> " + key + "\tvalue >>> " + value));
Gson gson = new Gson();
String json = gson.toJson(map);
System.out.println(json);

结果如下:

key >>> root	value >>> Emp(account=root, password=e10adc3949ba59abbe56e057f20f883e, name=李昊哲, gender=1, hiredate=Thu Oct 19 19:27:15 CST 2023, turnoverDate=null, createDate=2023-10-19, createDateTime=2023-10-19T19:27:15.788)
key >>> admin	value >>> Emp(account=admin, password=e10adc3949ba59abbe56e057f20f883e, name=李哲, gender=0, hiredate=Thu Oct 19 19:27:15 CST 2023, turnoverDate=null, createDate=2023-10-19, createDateTime=2023-10-19T19:27:15.790)
{"root":{"account":"root","password":"e10adc3949ba59abbe56e057f20f883e","name":"李昊哲","gender":1,"hiredate":"2023-10-19 19:27:15","createDate":"2023-10-19","createDateTime":"2023-10-19 19:27:15"},"admin":{"account":"admin","password":"e10adc3949ba59abbe56e057f20f883e","name":"李哲","gender":0,"hiredate":"2023-10-19 19:27:15","createDate":"2023-10-19","createDateTime":"2023-10-19 19:27:15"}}

json格式字符串转map

Map<String, Emp> map = new HashMap<>();
map.put("root", new Emp("root", "e10adc3949ba59abbe56e057f20f883e", "李昊哲", 1));
map.put("admin", new Emp("admin", "e10adc3949ba59abbe56e057f20f883e", "李哲", 0));
map.forEach((key, value) -> System.out.println("key >>> " + key + "\tvalue >>> " + value));
Gson gson = new Gson();
String json = gson.toJson(map);
System.out.println(json);
Map<String, Emp> empMap = gson.fromJson(json, new TypeToken<>() {
});
System.out.println(empMap);

结果如下:

key >>> root	value >>> Emp(account=root, password=e10adc3949ba59abbe56e057f20f883e, name=李昊哲, gender=1, hiredate=Thu Oct 19 19:27:15 CST 2023, turnoverDate=null, createDate=2023-10-19, createDateTime=2023-10-19T19:27:15.788)
key >>> admin	value >>> Emp(account=admin, password=e10adc3949ba59abbe56e057f20f883e, name=李哲, gender=0, hiredate=Thu Oct 19 19:27:15 CST 2023, turnoverDate=null, createDate=2023-10-19, createDateTime=2023-10-19T19:27:15.790)
{"root":{"account":"root","password":"e10adc3949ba59abbe56e057f20f883e","name":"李昊哲","gender":1,"hiredate":"2023-10-19 19:27:15","createDate":"2023-10-19","createDateTime":"2023-10-19 19:27:15"},"admin":{"account":"admin","password":"e10adc3949ba59abbe56e057f20f883e","name":"李哲","gender":0,"hiredate":"2023-10-19 19:27:15","createDate":"2023-10-19","createDateTime":"2023-10-19 19:27:15"}}
key >>> root	value >>> Emp(account=root, password=e10adc3949ba59abbe56e057f20f883e, name=李昊哲, gender=1, hiredate=Thu Oct 19 19:27:15 CST 2023, turnoverDate=null, createDate=2023-10-19, createDateTime=2023-10-19T19:27:15.788)
key >>> admin	value >>> Emp(account=admin, password=e10adc3949ba59abbe56e057f20f883e, name=李哲, gender=0, hiredate=Thu Oct 19 19:27:15 CST 2023, turnoverDate=null, createDate=2023-10-19, createDateTime=2023-10-19T19:27:15.790)

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/188655.html

(0)
飞熊的头像飞熊bm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!