原文:http://zetcode.com/java/gson/

Gson 教程展示了如何使用 Gson 库在 Java 中使用 JSON。 我们使用三种不同的 Gson API 来处理 JSON。 源代码可在作者的 Github 仓库中获得。

JSON(JavaScript 对象表示法)是一种轻量级的数据交换格式。 人类很容易读写,机器也很容易解析和生成。 与 XML 相比,它不那么冗长且更具可读性。 JSON 的官方互联网媒体类型为application/json。 JSON 文件扩展名是.json。 JSON 可直接由 JavaScript 使用。

Java Gson 库

Gson 是 Java 序列化/反序列化库,用于将 Java 对象转换为 JSON 并返回。 Gson 由 Google 创建,供内部使用,后来开源。

Java Gson Maven 依赖

  1. <dependency>
  2. <groupId>com.google.code.gson</groupId>
  3. <artifactId>gson</artifactId>
  4. <version>2.8.2</version>
  5. </dependency>

这是对 Gson 的 Maven 依赖。

Java Gson 特性

这些是 Gson 特性:

  • 用于 Java 对象 JSON 序列化和反序列化的简单工具。
  • Java 泛型的广泛支持。
  • 对象的自定义表示。
  • 支持任意复杂的对象。
  • 快速,低内存占用。
  • 允许紧凑的输出和漂亮的打印。

Java Gson API

Gson 具有三种 API:

  • 数据绑定 API
  • 树模型 API
  • 流 API

数据绑定 API 使用属性访问器将 JSON 与 POJO 之间进行转换。 Gson 使用数据类型适配器处理 JSON 数据。 它类似于 XML JAXB 解析器。

树模型 API 创建 JSON 文档的内存树表示。 它构建JsonElements的树。 它类似于 XML DOM 解析器。

流 API 是一种低级 API,它使用JsonReaderJsonWriter作为离散记号读取和写入 JSON 内容。 这些类将数据读取为JsonTokens。 该 API 具有最低的开销,并且在读/写操作中速度很快。 它类似于 XML 的 Stax 解析器。

Java Gson

Gson是使用 Gson 库的主要类。 有两种创建Gson的基本方法:

  • new Gson()
  • new GsonBuilder().create()

GsonBuilder可用于使用各种配置设置来构建Gson

Java Gson toJson()

toJson()方法将指定的对象序列化为其等效的 JSON 表示形式。

GsonToJson.java

  1. package com.zetcode;
  2. import com.google.gson.Gson;
  3. import java.util.HashMap;
  4. import java.util.Map;
  5. public class GsonToJson {
  6. public static void main(String[] args) {
  7. Map<Integer, String> colours = new HashMap<>();
  8. colours.put(1, "blue");
  9. colours.put(2, "yellow");
  10. colours.put(3, "green");
  11. Gson gson = new Gson();
  12. String output = gson.toJson(colours);
  13. System.out.println(output);
  14. }
  15. }

在示例中,我们使用toJSon()方法将映射序列化为 JSON。

  1. {"1":"blue","2":"yellow","3":"green"}

这是示例的输出。

Java Gson fromJson()

fromJson()方法将指定的 JSON 反序列化为指定类的对象。

GsonFromJson.java

  1. package com.zetcode;
  2. import com.google.gson.Gson;
  3. class User {
  4. private final String firstName;
  5. private final String lastName;
  6. public User(String firstName, String lastName) {
  7. this.firstName = firstName;
  8. this.lastName = lastName;
  9. }
  10. @Override
  11. public String toString() {
  12. return new StringBuilder().append("User{").append("First name: ")
  13. .append(firstName).append(", Last name: ")
  14. .append(lastName).append("}").toString();
  15. }
  16. }
  17. public class GsonFromJson {
  18. public static void main(String[] args) {
  19. String json_string = "{\"firstName\":\"Tom\", \"lastName\": \"Broody\"}";
  20. Gson gson = new Gson();
  21. User user = gson.fromJson(json_string, User.class);
  22. System.out.println(user);
  23. }
  24. }

该示例使用fromJson()方法将 JSON 读取到 Java 对象中。

  1. class User {
  2. private final String firstName;
  3. private final String lastName;
  4. public User(String firstName, String lastName) {
  5. this.firstName = firstName;
  6. this.lastName = lastName;
  7. }
  8. @Override
  9. public String toString() {
  10. return new StringBuilder().append("User{").append("First name: ")
  11. .append(firstName).append(", Last name: ")
  12. .append(lastName).append("}").toString();
  13. }
  14. }

注意,没有必要使用获取器和设置器方法。

  1. User{First name: Tom, Last name: Broody}

This is the output of the example.

GsonBuilder

GsonBuilder使用各种配置设置构建GsonGsonBuilder遵循构建器模式,通常通过首先调用各种配置方法来设置所需的选项,最后调用create()来使用它。

GsonBuilderEx.java

  1. package com.zetcode;
  2. import com.google.gson.FieldNamingPolicy;
  3. import com.google.gson.Gson;
  4. import com.google.gson.GsonBuilder;
  5. import java.io.IOException;
  6. import java.io.PrintStream;
  7. class User {
  8. private final String firstName;
  9. private final String lastName;
  10. public User(String firstName, String lastName) {
  11. this.firstName = firstName;
  12. this.lastName = lastName;
  13. }
  14. }
  15. public class GsonBuilderEx {
  16. public static void main(String[] args) throws IOException {
  17. try (PrintStream prs = new PrintStream(System.out, true,
  18. "UTF8")) {
  19. Gson gson = new GsonBuilder()
  20. .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
  21. .create();
  22. User user = new User("Peter", "Flemming");
  23. gson.toJson(user, prs);
  24. }
  25. }
  26. }

在示例中,我们将对象写入 JSON。 我们使用GsonBuilder创建Gson

  1. Gson gson = new GsonBuilder()
  2. .setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
  3. .create();

我们使用GsonBuilder创建并配置Gson。 字段命名策略设置为FieldNamingPolicy.UPPER_CAMEL_CASE

  1. {"FirstName":"Peter","LastName":"Flemming"}

这是输出。

Java Gson 漂亮打印

Gson 有两种输出模式:紧凑和漂亮。

GsonPrettyPrinting.java

  1. package com.zetcode;
  2. import com.google.gson.Gson;
  3. import com.google.gson.GsonBuilder;
  4. import java.util.HashMap;
  5. import java.util.Map;
  6. public class GsonPrettyPrinting {
  7. public static void main(String[] args) {
  8. Gson gson = new GsonBuilder().setPrettyPrinting().create();
  9. Map<String, Integer> items = new HashMap<>();
  10. items.put("chair", 3);
  11. items.put("pencil", 1);
  12. items.put("book", 5);
  13. gson.toJson(items, System.out);
  14. }
  15. }

该示例漂亮地显示了 JSON 输出。

  1. Gson gson = new GsonBuilder().setPrettyPrinting().create();

setPrettyPrinting()方法设置漂亮的打印模式。

  1. {
  2. "chair": 3,
  3. "book": 5,
  4. "pencil": 1
  5. }

This is the output of the example.

序列化空值

默认情况下,Gson 不会将具有空值的字段序列化为 JSON。 如果 Java 对象中的字段为null,则 Gson 会将其排除。 我们可以使用serializeNulls()方法强制 Gson 通过GsonBuilder序列化null值。

GsonSerializeNulls.java

  1. package com.zetcode;
  2. import com.google.gson.Gson;
  3. import com.google.gson.GsonBuilder;
  4. class User {
  5. private String firstName;
  6. private String lastName;
  7. public User() {};
  8. public User(String firstName, String lastName) {
  9. this.firstName = firstName;
  10. this.lastName = lastName;
  11. }
  12. public String getFirstName() {
  13. return firstName;
  14. }
  15. public void setFirstName(String firstName) {
  16. this.firstName = firstName;
  17. }
  18. public String getLastName() {
  19. return lastName;
  20. }
  21. public void setLastName(String lastName) {
  22. this.lastName = lastName;
  23. }
  24. @Override
  25. public String toString() {
  26. return new StringBuilder().append("User{").append("First name: ")
  27. .append(firstName).append(", Last name: ")
  28. .append(lastName).append("}").toString();
  29. }
  30. }
  31. public class GsonSerializeNulls {
  32. public static void main(String[] args) {
  33. GsonBuilder builder = new GsonBuilder();
  34. builder.serializeNulls();
  35. Gson gson = builder.create();
  36. User user = new User();
  37. user.setFirstName("Norman");
  38. String json = gson.toJson(user);
  39. System.out.println(json);
  40. }
  41. }

该示例显示了如何序列化null值。

  1. {"firstName":"Norman","lastName":null}

这是输出。

Java Gson 写入列表

以下示例将 JSON 对象列表写入文件。

GsonWriteList.java

  1. package com.zetcode;
  2. import com.google.gson.Gson;
  3. import java.io.FileOutputStream;
  4. import java.io.IOException;
  5. import java.io.OutputStreamWriter;
  6. import java.nio.charset.StandardCharsets;
  7. import java.util.ArrayList;
  8. import java.util.List;
  9. class Item {
  10. private final String name;
  11. private final int quantity;
  12. public Item(String name, int quantity) {
  13. this.name = name;
  14. this.quantity = quantity;
  15. }
  16. }
  17. public class GsonWriteList {
  18. public static void main(String[] args) throws IOException {
  19. String fileName = "src/main/resources/items.json";
  20. try (FileOutputStream fos = new FileOutputStream(fileName);
  21. OutputStreamWriter isr = new OutputStreamWriter(fos,
  22. StandardCharsets.UTF_8)) {
  23. Gson gson = new Gson();
  24. Item item1 = new Item("chair", 4);
  25. Item item2 = new Item("book", 5);
  26. Item item3 = new Item("pencil", 1);
  27. List<Item> items = new ArrayList<>();
  28. items.add(item1);
  29. items.add(item2);
  30. items.add(item3);
  31. gson.toJson(items, isr);
  32. }
  33. System.out.println("Items written to file");
  34. }
  35. }

该示例将 JSON 数据写入items.json文件。

Java Gson 读入数组

下一个示例将数据读取到 Java 数组中。

  1. $ cat users.json
  2. [{"firstName":"Peter","lastName":"Flemming"}, {"firstName":"Nicole","lastName":"White"},
  3. {"firstName":"Robin","lastName":"Bullock"} ]

这些是users.json文件的内容。

GsonReadArray.java

  1. package com.zetcode;
  2. import com.google.gson.Gson;
  3. import com.google.gson.GsonBuilder;
  4. import java.io.File;
  5. import java.io.IOException;
  6. import java.io.Reader;
  7. import java.nio.charset.StandardCharsets;
  8. import java.nio.file.Files;
  9. import java.nio.file.Path;
  10. import java.util.Arrays;
  11. class User {
  12. private final String firstName;
  13. private final String lastName;
  14. public User(String firstName, String lastName) {
  15. this.firstName = firstName;
  16. this.lastName = lastName;
  17. }
  18. @Override
  19. public String toString() {
  20. return new StringBuilder().append("{User").append("First name: ")
  21. .append(firstName).append(", Last name: ")
  22. .append(lastName).append("}").toString();
  23. }
  24. }
  25. public class GsonReadArray {
  26. public static void main(String[] args) throws IOException {
  27. Gson gson = new GsonBuilder().create();
  28. String fileName = "src/main/resources/users.json";
  29. Path path = new File(fileName).toPath();
  30. try (Reader reader = Files.newBufferedReader(path,
  31. StandardCharsets.UTF_8)) {
  32. User[] users = gson.fromJson(reader, User[].class);
  33. Arrays.stream(users).forEach( e -> {
  34. System.out.println(e);
  35. });
  36. }
  37. }
  38. }

该示例将items.json文件中的数据读取到数组中。 我们将数组的内容打印到控制台。

  1. User[] users = gson.fromJson(reader, User[].class);

fromJson()的第二个参数是数组类。

Java Gson 从 URL 读取 JSON

以下示例从网页读取 JSON 数据。 我们从http://time.jsontest.com获得 JSON 数据。

  1. {
  2. "time": "02:44:19 PM",
  3. "milliseconds_since_epoch": 1496155459478,
  4. "date": "05-30-2017"
  5. }

GET 请求返回此 JSON 字符串。

GsonReadWebPage.java

  1. package com.zetcode;
  2. import com.google.gson.Gson;
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.io.InputStreamReader;
  6. import java.io.Reader;
  7. import java.net.URL;
  8. import java.nio.charset.StandardCharsets;
  9. class TimeData {
  10. private String time;
  11. private Long milliseconds_since_epoch;
  12. private String date;
  13. @Override
  14. public String toString() {
  15. return "TimeData{" + "time=" + time + ", milliseconds_since_epoch="
  16. + milliseconds_since_epoch + ", date=" + date + '}';
  17. }
  18. }
  19. public class GsonReadWebPage {
  20. public static void main(String[] args) throws IOException {
  21. String webPage = "http://time.jsontest.com";
  22. try (InputStream is = new URL(webPage).openStream();
  23. Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8)) {
  24. Gson gson = new Gson();
  25. TimeData td = gson.fromJson(reader, TimeData.class);
  26. System.out.println(td);
  27. }
  28. }
  29. }

该代码示例从http://time.jsontest.com读取 JSON 数据。

  1. TimeData{time=11:23:09 PM, milliseconds_since_epoch=1516317789302, date=01-18-2018}

这是输出。

Java Gson 使用@Expose排除字段

@Expose注解指示应公开成员以进行 JSON 序列化或反序列化。 @Expose注解可以采用两个布尔参数:serializedeserialize。 必须使用excludeFieldsWithoutExposeAnnotation()方法显式启用@Expose注解。

GsonExcludeFields.java

  1. package com.zetcode;
  2. import com.google.gson.Gson;
  3. import com.google.gson.GsonBuilder;
  4. import com.google.gson.annotations.Expose;
  5. enum MaritalStatus {
  6. SINGLE,
  7. MARRIED,
  8. DIVORCED,
  9. UNKNOWN
  10. }
  11. class Person {
  12. @Expose
  13. private String firstName;
  14. @Expose
  15. private String lastName;
  16. private MaritalStatus maritalStatus;
  17. public Person(String firstName, String lastName,
  18. MaritalStatus maritalStatus) {
  19. this.firstName = firstName;
  20. this.lastName = lastName;
  21. this.maritalStatus = maritalStatus;
  22. }
  23. public Person() {}
  24. }
  25. public class GsonExcludeFields {
  26. public static void main(String[] args) {
  27. Gson gson = new GsonBuilder()
  28. .excludeFieldsWithoutExposeAnnotation()
  29. .setPrettyPrinting()
  30. .create();
  31. Person p = new Person("Jack", "Sparrow", MaritalStatus.UNKNOWN);
  32. gson.toJson(p, System.out);
  33. }
  34. }

在示例中,我们从序列化中排除一个字段。

  1. @Expose
  2. private String firstName;
  3. @Expose
  4. private String lastName;
  5. private MaritalStatus maritalStatus;

婚姻状况字段不会被序列化,因为它没有用@Expose注解修饰。

  1. Gson gson = new GsonBuilder()
  2. .excludeFieldsWithoutExposeAnnotation()
  3. .setPrettyPrinting()
  4. .create();

@Expose注解通过excludeFieldsWithoutExposeAnnotation()方法启用了字段排除。

  1. {
  2. "firstName": "Jack",
  3. "lastName": "Sparrow"
  4. }

这是输出。

Java Gson 数据绑定 API

数据绑定 API 使用属性访问器在 POJO 与 JSON 之间进行转换。 Gson 使用数据类型适配器处理 JSON 数据。

Gson 数据绑定 API 编写

在下面的示例中,我们使用数据绑定 API 编写数据。

GsonDataBindApiWrite.java

  1. package com.zetcode;
  2. import com.google.gson.Gson;
  3. import java.io.FileNotFoundException;
  4. import java.io.IOException;
  5. import java.io.Writer;
  6. import java.nio.charset.StandardCharsets;
  7. import java.nio.file.Files;
  8. import java.nio.file.Path;
  9. import java.nio.file.Paths;
  10. import java.util.ArrayList;
  11. import java.util.List;
  12. class Car {
  13. private final String name;
  14. private final String model;
  15. private final int price;
  16. private final String[] colours;
  17. public Car(String name, String model, int price, String[] colours) {
  18. this.name = name;
  19. this.model = model;
  20. this.price = price;
  21. this.colours = colours;
  22. }
  23. }
  24. public class GsonDataBindApiWrite {
  25. public static void main(String[] args) throws FileNotFoundException, IOException {
  26. List<Car> cars = new ArrayList<>();
  27. cars.add(new Car("Audi", "2012", 22000, new String[]{"gray", "red", "white"}));
  28. cars.add(new Car("Skoda", "2016", 14000, new String[]{"black", "gray", "white"}));
  29. cars.add(new Car("Volvo", "2010", 19500, new String[]{"black", "silver", "beige"}));
  30. String fileName = "src/main/resources/cars.json";
  31. Path path = Paths.get(fileName);
  32. try (Writer writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
  33. Gson gson = new Gson();
  34. gson.toJson(cars, writer);
  35. }
  36. System.out.println("Cars written to file");
  37. }
  38. }

在示例中,我们创建了一个汽车对象列表,并使用 Gson 数据绑定 API 对其进行了序列化。

  1. Gson gson = new Gson();
  2. gson.toJson(cars, writer);

我们将cars列表传递给toJson()方法。 Gson 自动将汽车对象映射到 JSON。

读取 Gson 数据绑定 API

在下面的示例中,我们使用数据绑定 API 读取数据。

GsonDataBindingApiRead.java

  1. package com.zetcode;
  2. import com.google.gson.Gson;
  3. import com.google.gson.reflect.TypeToken;
  4. import java.io.FileNotFoundException;
  5. import java.io.IOException;
  6. import java.io.Reader;
  7. import java.nio.charset.StandardCharsets;
  8. import java.nio.file.Files;
  9. import java.nio.file.Path;
  10. import java.nio.file.Paths;
  11. import java.util.Arrays;
  12. import java.util.List;
  13. class Car {
  14. private final String name;
  15. private final String model;
  16. private final int price;
  17. private final String[] colours;
  18. public Car(String name, String model, int price, String[] colours) {
  19. this.name = name;
  20. this.model = model;
  21. this.price = price;
  22. this.colours = colours;
  23. }
  24. @Override
  25. public String toString() {
  26. return "Car{" + "name=" + name + ", model=" + model +
  27. ", price=" + price + ", colours=" + Arrays.toString(colours) + '}';
  28. }
  29. }
  30. public class GsonDataBindingApiRead {
  31. public static void main(String[] args) throws FileNotFoundException, IOException {
  32. String fileName = "src/main/resources/cars.json";
  33. Path path = Paths.get(fileName);
  34. try (Reader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
  35. Gson gson = new Gson();
  36. List<Car> cars = gson.fromJson(reader,
  37. new TypeToken<List<Car>>(){}.getType());
  38. cars.forEach(System.out::println);
  39. }
  40. }
  41. }

在示例中,我们使用 Gson 数据绑定 API 将数据从 JSON 文件读取到汽车对象列表中。

  1. List<Car> cars = gson.fromJson(reader,
  2. new TypeToken<List<Car>>(){}.getType());

Gson 自动将 JSON 映射到Car对象。 由于类型信息在运行时会丢失,因此我们需要使用TypeToken让 Gson 知道我们使用的是哪种类型。

Java Gson 树模型 API

树模型 API 在内存中创建 JSON 文档的树表示。 它构建JsonElements的树。 JsonElement是代表 Json 元素的类。 它可以是JsonObjectJsonArrayJsonPrimitiveJsonNull

Gson 树模型写

在以下示例中,我们使用 Gson 树模型 API 将 Java 对象写入 JSON。

GsonTreeModelWrite.java

  1. package com.zetcode;
  2. import com.google.gson.Gson;
  3. import com.google.gson.JsonArray;
  4. import com.google.gson.JsonElement;
  5. import com.google.gson.JsonObject;
  6. import java.io.FileNotFoundException;
  7. import java.io.IOException;
  8. import java.io.Writer;
  9. import java.nio.charset.StandardCharsets;
  10. import java.nio.file.Files;
  11. import java.nio.file.Path;
  12. import java.nio.file.Paths;
  13. import java.util.ArrayList;
  14. import java.util.List;
  15. class Car {
  16. private final String name;
  17. private final String model;
  18. private final int price;
  19. private final String[] colours;
  20. public Car(String name, String model, int price, String[] colours) {
  21. this.name = name;
  22. this.model = model;
  23. this.price = price;
  24. this.colours = colours;
  25. }
  26. }
  27. public class GsonTreeModelWrite {
  28. public static void main(String[] args) throws FileNotFoundException, IOException {
  29. List<Car> cars = new ArrayList<>();
  30. cars.add(new Car("Audi", "2012", 22000,
  31. new String[]{"gray", "red", "white"}));
  32. cars.add(new Car("Skoda", "2016", 14000,
  33. new String[]{"black", "gray", "white"}));
  34. cars.add(new Car("Volvo", "2010", 19500,
  35. new String[]{"black", "silver", "beige"}));
  36. String fileName = "src/main/resources/cars.json";
  37. Path path = Paths.get(fileName);
  38. try (Writer writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
  39. Gson gson = new Gson();
  40. JsonElement tree = gson.toJsonTree(cars);
  41. gson.toJson(tree, writer);
  42. }
  43. System.out.println("Cars written to file");
  44. }
  45. }

汽车对象列表被序列化为 JSON 格式。

  1. JsonElement tree = gson.toJsonTree(cars);

toJsonTree方法将指定的对象序列化为其等效表示形式,作为JsonElements的树。

  1. JsonArray jarray = tree.getAsJsonArray();

我们使用getAsJsonArray()方法将树转换为JsonArray

  1. JsonElement jel = jarray.get(1);

我们从数组中获取第二个元素。

  1. JsonObject object = jel.getAsJsonObject();
  2. object.addProperty("model", "2009");

我们修改一个属性。

  1. gson.toJson(tree, writer);

最后,我们将树对象写入文件中。

Gson 树模型读取

在以下示例中,我们使用 Gson 树模型 API 从 JSON 读取 Java 对象。

cars.json

  1. [{"name":"Audi","model":"2012","price":22000,"colours":["gray","red","white"]},
  2. {"name":"Skoda","model":"2009","price":14000,"colours":["black","gray","white"]},
  3. {"name":"Volvo","model":"2010","price":19500,"colours":["black","silver","beige"]}]

这是cars.json文件中的 JSON 数据。

GsonTreeModelRead.java

  1. package com.zetcode;
  2. import com.google.gson.JsonArray;
  3. import com.google.gson.JsonElement;
  4. import com.google.gson.JsonObject;
  5. import com.google.gson.JsonParser;
  6. import java.io.FileNotFoundException;
  7. import java.io.IOException;
  8. import java.io.Reader;
  9. import java.nio.charset.StandardCharsets;
  10. import java.nio.file.Files;
  11. import java.nio.file.Path;
  12. import java.nio.file.Paths;
  13. public class GsonTreeModelRead {
  14. public static void main(String[] args) throws FileNotFoundException, IOException {
  15. String fileName = "src/main/resources/cars.json";
  16. Path path = Paths.get(fileName);
  17. try (Reader reader = Files.newBufferedReader(path,
  18. StandardCharsets.UTF_8)) {
  19. JsonParser parser = new JsonParser();
  20. JsonElement tree = parser.parse(reader);
  21. JsonArray array = tree.getAsJsonArray();
  22. for (JsonElement element : array) {
  23. if (element.isJsonObject()) {
  24. JsonObject car = element.getAsJsonObject();
  25. System.out.println("********************");
  26. System.out.println(car.get("name").getAsString());
  27. System.out.println(car.get("model").getAsString());
  28. System.out.println(car.get("price").getAsInt());
  29. JsonArray cols = car.getAsJsonArray("colors");
  30. cols.forEach(col -> {
  31. System.out.println(col);
  32. });
  33. }
  34. }
  35. }
  36. }
  37. }

在示例中,我们将 JSON 数据从文件读取到JsonElements树中。

  1. JsonParser parser = new JsonParser();
  2. JsonElement tree = parser.parse(reader);

JsonParser将 JSON 解析为JsonElements的树结构。

  1. JsonArray array = tree.getAsJsonArray();

我们将树作为JsonArray

  1. for (JsonElement element : array) {
  2. if (element.isJsonObject()) {
  3. JsonObject car = element.getAsJsonObject();
  4. System.out.println("********************");
  5. System.out.println(car.get("name").getAsString());
  6. System.out.println(car.get("model").getAsString());
  7. System.out.println(car.get("price").getAsInt());
  8. JsonArray cols = car.getAsJsonArray("colors");
  9. cols.forEach(col -> {
  10. System.out.println(col);
  11. });
  12. }
  13. }

我们浏览JsonArray并打印其元素的内容。

Java Gson 流 API

Gson 流 API 是一个低级 API,它以离散记号(JsonTokens)的形式读取和写入 JSON。 主要类别是JsonReaderJsonWriterJsonToken是 JSON 编码的字符串中的结构,名称或值类型。

这些是JsonToken类型:

  • BEGIN_ARRAY — 打开 JSON 数组
  • END_ARRAY — 关闭 JSON 数组
  • BEGIN_OBJECT — 打开 JSON 对象
  • END_OBJECT — 关闭 JSON 对象
  • NAME - JSON 属性名称
  • STRING — JSON 字符串
  • NUMBER — JSON 数字(双精度,长整型或整型)
  • BOOLEAN — JSON 布尔值
  • NULL — JSON 空值
  • END_DOCUMENT — JSON 流的末尾。

JsonWriter

JsonWriter将 JSON 编码值写入流,一次写入一个记号。 流包含字面值(字符串,数字,布尔值和null)以及对象和数组的开始和结束定界符。 每个 JSON 文档必须包含一个顶级数组或对象。

使用beginObject()endObject()方法调用创建对象。 在对象内,标记在名称及其值之间交替。 在beginArray()endArray()方法调用中创建数组。

GsonStreamApiWrite.java

  1. package com.zetcode;
  2. import com.google.gson.stream.JsonWriter;
  3. import java.io.IOException;
  4. import java.nio.charset.StandardCharsets;
  5. import java.nio.file.Files;
  6. import java.nio.file.Path;
  7. import java.nio.file.Paths;
  8. public class GsonStreamApiWrite {
  9. public static void main(String[] args) throws IOException {
  10. String fileName = "src/main/resources/cars.json";
  11. Path path = Paths.get(fileName);
  12. try (JsonWriter writer = new JsonWriter(Files.newBufferedWriter(path,
  13. StandardCharsets.UTF_8))) {
  14. writer.beginObject();
  15. writer.name("name").value("Audi");
  16. writer.name("model").value("2012");
  17. writer.name("price").value(22000);
  18. writer.name("colours");
  19. writer.beginArray();
  20. writer.value("gray");
  21. writer.value("red");
  22. writer.value("white");
  23. writer.endArray();
  24. writer.endObject();
  25. }
  26. System.out.println("Data written to file");
  27. }
  28. }

在示例中,我们将一个汽车对象写入 JSON 文件。

  1. try (JsonWriter writer = new JsonWriter(Files.newBufferedWriter(path,
  2. StandardCharsets.UTF_8))) {

创建一个新的JsonWriter

  1. writer.beginObject();
  2. ...
  3. writer.endObject();

如上所述,每个 JSON 文档必须具有一个顶级数组或对象。 在我们的例子中,我们有一个顶级对象。

  1. writer.name("name").value("Audi");
  2. writer.name("model").value("2012");
  3. writer.name("price").value(22000);

我们将键值对写入文档。

  1. writer.name("colours");
  2. writer.beginArray();
  3. writer.value("gray");
  4. writer.value("red");
  5. writer.value("white");
  6. writer.endArray();

在这里,我们创建一个数组。

JsonReader

JsonReader读取 JSON 编码值作为记号流。

GsonStreamApiRead.java

  1. package com.zetcode;
  2. import com.google.gson.stream.JsonReader;
  3. import com.google.gson.stream.JsonToken;
  4. import java.io.IOException;
  5. import java.io.StringReader;
  6. public class GsonStreamApiRead {
  7. public static void main(String[] args) throws IOException {
  8. String json_string = "{\"name\":\"chair\",\"quantity\":3}";
  9. try (JsonReader reader = new JsonReader(new StringReader(json_string))) {
  10. while (reader.hasNext()) {
  11. JsonToken nextToken = reader.peek();
  12. if (JsonToken.BEGIN_OBJECT.equals(nextToken)) {
  13. reader.beginObject();
  14. } else if (JsonToken.NAME.equals(nextToken)) {
  15. reader.nextName();
  16. } else if (JsonToken.STRING.equals(nextToken)) {
  17. String value = reader.nextString();
  18. System.out.format("%s: ", value);
  19. } else if (JsonToken.NUMBER.equals(nextToken)) {
  20. long value = reader.nextLong();
  21. System.out.println(value);
  22. }
  23. }
  24. }
  25. }
  26. }

该示例使用JsonReader从 JSON 字符串读取数据。

  1. JsonReader reader = new JsonReader(new StringReader(json_string));

JsonReader对象已创建。 它从 JSON 字符串读取。

  1. while (reader.hasNext()) {

while循环中,我们迭代流中的记号。

  1. JsonToken nextToken = reader.peek();

我们使用peek()方法获得下一个标记的类型。

  1. reader.beginObject();

beginObject()方法使用 JSON 流中的下一个记号,并断言它是新对象的开始。

  1. reader.nextName();

nextName()方法返回下一个JsonToken并使用它。

  1. String value = reader.nextString();
  2. System.out.format("%s: ", value);

我们获取下一个字符串值并将其打印到控制台。

在本教程中,我们展示了如何通过 Gson 库使用 JSON。 您可能也对相关教程感兴趣: Jsoup 教程Java JSON 处理教程Java8 forEach教程用 Java 读取文本文件Java 教程