Java GSON 解析 JSON 完全指南

1. 简介

GSON(Google JSON)是 Google 提供的用于在 Java 中处理 JSON 数据的库。它允许 Java 对象与 JSON 之间进行序列化和反序列化,支持简单对象、集合、泛型和复杂数据结构的转换。GSON 轻量、高效、易用,是 Java 开发中处理 JSON 的常见选择。

2. 目录

  1. GSON 简介
  2. GSON 安装
  3. 基本用法
    • Java 对象转换为 JSON
    • JSON 转换为 Java 对象
  4. 复杂 JSON 解析
    • 解析 JSON 数组
    • 解析嵌套 JSON
    • 解析泛型对象
  5. 自定义序列化与反序列化
  6. GSON 高级特性
  7. 最佳实践
  8. 总结
  9. 参考资料

3. GSON 安装

Maven 依赖

如果你使用 Maven,可以在 pom.xml 文件中添加:

<dependencies>
    <dependency>
        <groupId>com.google.code.gsongroupId>
        <artifactId>gsonartifactId>
        <version>2.10.1version>
    dependency>
dependencies>
Gradle 依赖
dependencies {
    implementation 'com.google.code.gson:gson:2.10.1'
}
手动下载

如果不使用构建工具,可以从 GSON 官方 GitHub 下载 .jar 并添加到项目的 lib 目录中。


4. 基本用法

Java 对象转换为 JSON(序列化)
import com.google.gson.Gson;

class Person {
    String name;
    int age;

    Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

public class GsonExample {
    public static void main(String[] args) {
        Gson gson = new Gson();
        Person person = new Person("张三", 25);
        String json = gson.toJson(person);
        System.out.println(json); // {"name":"张三","age":25}
    }
}
JSON 转换为 Java 对象(反序列化)
import com.google.gson.Gson;

public class GsonExample {
    public static void main(String[] args) {
        String json = "{\"name\":\"张三\",\"age\":25}";
        Gson gson = new Gson();
        Person person = gson.fromJson(json, Person.class);
        System.out.println(person.name + " - " + person.age);
    }
}

5. 复杂 JSON 解析

解析 JSON 数组
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
import java.util.List;

public class GsonArrayExample {
    public static void main(String[] args) {
        String json = "[{\"name\":\"张三\",\"age\":25}, {\"name\":\"李四\",\"age\":30}]";
        Gson gson = new Gson();

        Type listType = new TypeToken<List<Person>>() {}.getType();
        List<Person> personList = gson.fromJson(json, listType);

        for (Person p : personList) {
            System.out.println(p.name + " - " + p.age);
        }
    }
}
解析嵌套 JSON
class Address {
    String city;
    String country;
}

class User {
    String name;
    int age;
    Address address;
}

public class GsonNestedExample {
    public static void main(String[] args) {
        String json = "{ \"name\": \"张三\", \"age\": 25, \"address\": { \"city\": \"北京\", \"country\": \"中国\" } }";
        Gson gson = new Gson();
        User user = gson.fromJson(json, User.class);

        System.out.println(user.name + " - " + user.address.city);
    }
}
解析泛型对象
class Response<T> {
    int code;
    T data;
}

public class GsonGenericExample {
    public static void main(String[] args) {
        String json = "{ \"code\": 200, \"data\": { \"name\": \"张三\", \"age\": 25 } }";
        Gson gson = new Gson();

        Type type = new TypeToken<Response<Person>>() {}.getType();
        Response<Person> response = gson.fromJson(json, type);

        System.out.println(response.code + " - " + response.data.name);
    }
}

6. 自定义序列化与反序列化

有时,我们需要自定义 JSON 的格式。例如,修改日期格式或忽略某些字段。

忽略某些字段
import com.google.gson.annotations.Expose;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

class User {
    @Expose
    String name;

    @Expose
    int age;

    String password;
}

public class GsonCustomSerialization {
    public static void main(String[] args) {
        User user = new User();
        user.name = "张三";
        user.age = 25;
        user.password = "secret";

        Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
        System.out.println(gson.toJson(user)); // {"name":"张三","age":25}
    }
}
自定义日期格式
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.Date;

class Event {
    String name;
    Date date;
}

public class GsonDateFormatExample {
    public static void main(String[] args) {
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        Event event = new Event();
        event.name = "会议";
        event.date = new Date();

        String json = gson.toJson(event);
        System.out.println(json);
    }
}

7. GSON 高级特性

  • GsonBuilder 配置:可以启用更强大的特性,如 setPrettyPrinting()(美化 JSON)、serializeNulls()(序列化 null 值)。
  • 流式解析:使用 JsonReaderJsonWriter 进行高效的流式 JSON 解析。
  • 自定义类型适配器:可以创建 TypeAdapter 来控制序列化和反序列化过程。

8. 最佳实践

  1. 使用 GsonBuilder 来控制序列化规则(例如忽略 null 值)。
  2. 在复杂数据结构中使用 TypeToken 解析泛型对象。
  3. 使用 @Expose 注解 保护敏感数据,防止某些字段被序列化。
  4. 处理 JSON 异常,避免 JsonSyntaxExceptionNullPointerException
  5. 使用流式解析 处理大规模 JSON 数据,提高性能。

9. 总结

GSON 是 Java 处理 JSON 的强大工具,提供了简单易用的 API 来完成对象与 JSON 之间的转换。本文涵盖了基本使用、复杂解析、自定义序列化、以及最佳实践,希望能帮助你在 Java 项目中高效使用 GSON。


10. 参考资料

  • GSON 官方文档
  • GSON API 参考

你可能感兴趣的:(java,json,开发语言)