原文:https://geek-docs.com/java/java-tutorial/gson.html
Gson教程展示了如何使用Gson庫(kù)在Java中使用JSON。我們使用三種不同的Gson API來(lái)處理JSON。源代碼可在作者的Github存儲(chǔ)庫(kù)中獲得。
JSON(JavaScript對(duì)象表示法)是一種輕量級(jí)的數(shù)據(jù)交換格式。人類很容易讀寫,機(jī)器也很容易解析和生成。與XML相比,它不那么冗長(zhǎng)且更具可讀性。JSON的官方Internet媒體類型為application/json。JSON文件擴(kuò)展名是.json。JSON可直接由JavaScript使用。
Java Gson 庫(kù)
Gson是Java序列化/反序列化庫(kù),用于將Java對(duì)象轉(zhuǎn)換為JSON并返回。Gson由Google創(chuàng)建,供內(nèi)部使用,后來(lái)開(kāi)源。
Java Gson Maven 依賴
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.2</version>
</dependency>
這是對(duì)Gson的Maven依賴。
Java Gson 特性
這些是Gson特性:
- 用于
Java對(duì)象JSON序列化和反序列化的簡(jiǎn)單工具。 -
Java泛型的廣泛支持。 - 對(duì)象的自定義表示。
- 支持任意復(fù)雜的對(duì)象。
- 快速,低內(nèi)存占用。
- 允許緊湊的輸出和漂亮的打印。
Java Gson API
Gson具有三種API:
- 數(shù)據(jù)綁定
API - 樹模型
API - 流
API
數(shù)據(jù)綁定API使用屬性訪問(wèn)器將JSON與POJO之間進(jìn)行轉(zhuǎn)換。Gson使用數(shù)據(jù)類型適配器處理JSON數(shù)據(jù)。它類似于XML JAXB解析器。
樹模型API創(chuàng)建JSON文檔的內(nèi)存樹表示。它構(gòu)建JsonElements的樹。它類似于XML DOM解析器。
流API是一種低級(jí)API,它使用JsonReader和JsonWriter作為離散記號(hào)讀取和寫入JSON內(nèi)容。這些類將數(shù)據(jù)讀取為JsonTokens。該API具有最低的開(kāi)銷,并且在讀/寫操作中速度很快。它類似于XML的Stax解析器。
Java Gson 類
Gson是使用Gson庫(kù)的主要類。 有兩種創(chuàng)建Gson的基本方法:
- 新
Gson() - 新的
GsonBuilder().create()
GsonBuilder可用于使用各種配置設(shè)置來(lái)構(gòu)建Gson。
Java GsontoJson()
toJson()方法將指定的對(duì)象序列化為其等效的JSON表示形式。
GsonToJson.java
package com.zetcode;
import com.google.gson.Gson;
import java.util.HashMap;
import java.util.Map;
public class GsonToJson {
public static void main(String[] args) {
Map<Integer, String> colours = new HashMap<>();
colours.put(1, "blue");
colours.put(2, "yellow");
colours.put(3, "green");
Gson gson = new Gson();
String output = gson.toJson(colours);
System.out.println(output);
}
}
在示例中,我們使用toJSon()方法將映射序列化為JSON。
{"1":"blue","2":"yellow","3":"green"}
這是示例的輸出。
Java GsonfromJson()
fromJson()方法將指定的JSON反序列化為指定類的對(duì)象。
GsonFromJson.java
package com.zetcode;
import com.google.gson.Gson;
class User {
private final String firstName;
private final String lastName;
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public String toString() {
return new StringBuilder().append("User{").append("First name: ")
.append(firstName).append(", Last name: ")
.append(lastName).append("}").toString();
}
}
public class GsonFromJson {
public static void main(String[] args) {
String json_string = "{\"firstName\":\"Tom\", \"lastName\": \"Broody\"}";
Gson gson = new Gson();
User user = gson.fromJson(json_string, User.class);
System.out.println(user);
}
}
該示例使用fromJson()方法將JSON讀取到Java對(duì)象中。
class User {
private final String firstName;
private final String lastName;
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public String toString() {
return new StringBuilder().append("User{").append("First name: ")
.append(firstName).append(", Last name: ")
.append(lastName).append("}").toString();
}
}
注意,沒(méi)有必要使用getter和setter方法。
User{First name: Tom, Last name: Broody}
This is the output of the example.
GsonBuilder
GsonBuilder使用各種配置設(shè)置構(gòu)建Gson。 GsonBuilder遵循構(gòu)建器模式,通常通過(guò)首先調(diào)用各種配置方法來(lái)設(shè)置所需的選項(xiàng),最后調(diào)用create()來(lái)使用它。
GsonBuilderEx.java
package com.zetcode;
import com.google.gson.FieldNamingPolicy;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.IOException;
import java.io.PrintStream;
class User {
private final String firstName;
private final String lastName;
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
}
public class GsonBuilderEx {
public static void main(String[] args) throws IOException {
try (PrintStream prs = new PrintStream(System.out, true,
"UTF8")) {
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
.create();
User user = new User("Peter", "Flemming");
gson.toJson(user, prs);
}
}
}
在示例中,我們將對(duì)象寫入JSON。 我們使用GsonBuilder創(chuàng)建Gson。
Gson gson = new GsonBuilder()
.setFieldNamingPolicy(FieldNamingPolicy.UPPER_CAMEL_CASE)
.create();
我們使用GsonBuilder創(chuàng)建并配置Gson。字段命名策略設(shè)置為FieldNamingPolicy.UPPER_CAMEL_CASE。
{"FirstName":"Peter","LastName":"Flemming"}
這是輸出。
Java Gson 漂亮打印
Gson有兩種輸出模式:緊湊和漂亮。
GsonPrettyPrinting.java
package com.zetcode;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.HashMap;
import java.util.Map;
public class GsonPrettyPrinting {
public static void main(String[] args) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
Map<String, Integer> items = new HashMap<>();
items.put("chair", 3);
items.put("pencil", 1);
items.put("book", 5);
gson.toJson(items, System.out);
}
}
該示例漂亮地顯示了JSON輸出。
Gson gson = new GsonBuilder().setPrettyPrinting().create();
setPrettyPrinting()方法設(shè)置漂亮的打印模式。
{
"chair": 3,
"book": 5,
"pencil": 1
}
This is the output of the example.
序列化空值
默認(rèn)情況下,Gson不會(huì)將具有空值的字段序列化為JSON。如果Java對(duì)象中的字段為null,則Gson會(huì)將其排除。我們可以使用serializeNulls()方法強(qiáng)制 Gson通過(guò)GsonBuilder序列化null值。
GsonSerializeNulls.java
package com.zetcode;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
class User {
private String firstName;
private String lastName;
public User() {};
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
@Override
public String toString() {
return new StringBuilder().append("User{").append("First name: ")
.append(firstName).append(", Last name: ")
.append(lastName).append("}").toString();
}
}
public class GsonSerializeNulls {
public static void main(String[] args) {
GsonBuilder builder = new GsonBuilder();
builder.serializeNulls();
Gson gson = builder.create();
User user = new User();
user.setFirstName("Norman");
String json = gson.toJson(user);
System.out.println(json);
}
}
該示例顯示了如何序列化null值。
{"firstName":"Norman","lastName":null}
This is the output.
Java Gson 寫入列表
以下示例將JSON對(duì)象列表寫入文件。
GsonWriteList.java
package com.zetcode;
import com.google.gson.Gson;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
class Item {
private final String name;
private final int quantity;
public Item(String name, int quantity) {
this.name = name;
this.quantity = quantity;
}
}
public class GsonWriteList {
public static void main(String[] args) throws IOException {
String fileName = "src/main/resources/items.json";
try (FileOutputStream fos = new FileOutputStream(fileName);
OutputStreamWriter isr = new OutputStreamWriter(fos,
StandardCharsets.UTF_8)) {
Gson gson = new Gson();
Item item1 = new Item("chair", 4);
Item item2 = new Item("book", 5);
Item item3 = new Item("pencil", 1);
List<Item> items = new ArrayList<>();
items.add(item1);
items.add(item2);
items.add(item3);
gson.toJson(items, isr);
}
System.out.println("Items written to file");
}
}
該示例將JSON數(shù)據(jù)寫入items.json文件。
Java Gson 讀入數(shù)組
下一個(gè)示例將數(shù)據(jù)讀取到Java數(shù)組中。
$ cat users.json
[{"firstName":"Peter","lastName":"Flemming"}, {"firstName":"Nicole","lastName":"White"},
{"firstName":"Robin","lastName":"Bullock"} ]
這些是users.json文件的內(nèi)容。
GsonReadArray.java
package com.zetcode;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Arrays;
class User {
private final String firstName;
private final String lastName;
public User(String firstName, String lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
@Override
public String toString() {
return new StringBuilder().append("{User").append("First name: ")
.append(firstName).append(", Last name: ")
.append(lastName).append("}").toString();
}
}
public class GsonReadArray {
public static void main(String[] args) throws IOException {
Gson gson = new GsonBuilder().create();
String fileName = "src/main/resources/users.json";
Path path = new File(fileName).toPath();
try (Reader reader = Files.newBufferedReader(path,
StandardCharsets.UTF_8)) {
User[] users = gson.fromJson(reader, User[].class);
Arrays.stream(users).forEach( e -> {
System.out.println(e);
});
}
}
}
該示例將items.json文件中的數(shù)據(jù)讀取到數(shù)組中。 我們將數(shù)組的內(nèi)容打印到控制臺(tái)。
User[] users = gson.fromJson(reader, User[].class);
fromJson()的第二個(gè)參數(shù)是數(shù)組類。
Java Gson從URL讀取JSON
以下示例從網(wǎng)頁(yè)讀取JSON數(shù)據(jù)。我們從http://time.jsontest.com獲得JSON數(shù)據(jù)。
{
"time": "02:44:19 PM",
"milliseconds_since_epoch": 1496155459478,
"date": "05-30-2017"
}
GET請(qǐng)求返回此JSON字符串。
GsonReadWebPage.java
package com.zetcode;
import com.google.gson.Gson;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
class TimeData {
private String time;
private Long milliseconds_since_epoch;
private String date;
@Override
public String toString() {
return "TimeData{" + "time=" + time + ", milliseconds_since_epoch="
+ milliseconds_since_epoch + ", date=" + date + '}';
}
}
public class GsonReadWebPage {
public static void main(String[] args) throws IOException {
String webPage = "http://time.jsontest.com";
try (InputStream is = new URL(webPage).openStream();
Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8)) {
Gson gson = new Gson();
TimeData td = gson.fromJson(reader, TimeData.class);
System.out.println(td);
}
}
}
該代碼示例從http://time.jsontest.com讀取JSON數(shù)據(jù)。
TimeData{time=11:23:09 PM, milliseconds_since_epoch=1516317789302, date=01-18-2018}
This is the output.
Java Gson使用@Expose排除字段
@Expose注解指示應(yīng)公開(kāi)成員以進(jìn)行JSON序列化或反序列化。 @Expose注解可以采用兩個(gè)布爾參數(shù):serialize和deserialize。 必須使用excludeFieldsWithoutExposeAnnotation()方法顯式啟用@Expose注解。
GsonExcludeFields.java
package com.zetcode;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.annotations.Expose;
enum MaritalStatus {
SINGLE,
MARRIED,
DIVORCED,
UNKNOWN
}
class Person {
@Expose
private String firstName;
@Expose
private String lastName;
private MaritalStatus maritalStatus;
public Person(String firstName, String lastName,
MaritalStatus maritalStatus) {
this.firstName = firstName;
this.lastName = lastName;
this.maritalStatus = maritalStatus;
}
public Person() {}
}
public class GsonExcludeFields {
public static void main(String[] args) {
Gson gson = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
.setPrettyPrinting()
.create();
Person p = new Person("Jack", "Sparrow", MaritalStatus.UNKNOWN);
gson.toJson(p, System.out);
}
}
在示例中,我們從序列化中排除一個(gè)字段。
@Expose
private String firstName;
@Expose
private String lastName;
private MaritalStatus maritalStatus;
婚姻狀況字段不會(huì)被序列化,因?yàn)樗鼪](méi)有用@Expose注解修飾。
Gson gson = new GsonBuilder()
.excludeFieldsWithoutExposeAnnotation()
.setPrettyPrinting()
.create();
@Expose注解通過(guò)excludeFieldsWithoutExposeAnnotation()方法啟用了字段排除。
{
"firstName": "Jack",
"lastName": "Sparrow"
}
This is the output.
Java Gson 數(shù)據(jù)綁定 API
數(shù)據(jù)綁定API使用屬性訪問(wèn)器在POJO與JSON之間進(jìn)行轉(zhuǎn)換。Gson使用數(shù)據(jù)類型適配器處理JSON數(shù)據(jù)。
Gson 數(shù)據(jù)綁定 API 編寫
在下面的示例中,我們使用數(shù)據(jù)綁定API編寫數(shù)據(jù)。
GsonDataBindApiWrite.java
package com.zetcode;
import com.google.gson.Gson;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
class Car {
private final String name;
private final String model;
private final int price;
private final String[] colours;
public Car(String name, String model, int price, String[] colours) {
this.name = name;
this.model = model;
this.price = price;
this.colours = colours;
}
}
public class GsonDataBindApiWrite {
public static void main(String[] args) throws FileNotFoundException, IOException {
List<Car> cars = new ArrayList<>();
cars.add(new Car("Audi", "2012", 22000, new String[]{"gray", "red", "white"}));
cars.add(new Car("Skoda", "2016", 14000, new String[]{"black", "gray", "white"}));
cars.add(new Car("Volvo", "2010", 19500, new String[]{"black", "silver", "beige"}));
String fileName = "src/main/resources/cars.json";
Path path = Paths.get(fileName);
try (Writer writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
Gson gson = new Gson();
gson.toJson(cars, writer);
}
System.out.println("Cars written to file");
}
}
在示例中,我們創(chuàng)建了一個(gè)汽車對(duì)象列表,并使用Gson數(shù)據(jù)綁定API對(duì)其進(jìn)行了序列化。
Gson gson = new Gson();
gson.toJson(cars, writer);
我們將cars列表傳遞給toJson()方法。Gson自動(dòng)將汽車對(duì)象映射到JSON。
讀取Gson數(shù)據(jù)綁定API
在下面的示例中,我們使用數(shù)據(jù)綁定API讀取數(shù)據(jù)。
GsonDataBindingApiRead.java
package com.zetcode;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.List;
class Car {
private final String name;
private final String model;
private final int price;
private final String[] colours;
public Car(String name, String model, int price, String[] colours) {
this.name = name;
this.model = model;
this.price = price;
this.colours = colours;
}
@Override
public String toString() {
return "Car{" + "name=" + name + ", model=" + model +
", price=" + price + ", colours=" + Arrays.toString(colours) + '}';
}
}
public class GsonDataBindingApiRead {
public static void main(String[] args) throws FileNotFoundException, IOException {
String fileName = "src/main/resources/cars.json";
Path path = Paths.get(fileName);
try (Reader reader = Files.newBufferedReader(path, StandardCharsets.UTF_8)) {
Gson gson = new Gson();
List<Car> cars = gson.fromJson(reader,
new TypeToken<List<Car>>(){}.getType());
cars.forEach(System.out::println);
}
}
}
在示例中,我們使用Gson數(shù)據(jù)綁定API將數(shù)據(jù)從JSON文件讀取到汽車對(duì)象列表中。
List<Car> cars = gson.fromJson(reader,
new TypeToken<List<Car>>(){}.getType());
Gson自動(dòng)將JSON映射到Car對(duì)象。由于類型信息在運(yùn)行時(shí)會(huì)丟失,因此我們需要使用TypeToken讓Gson知道我們使用的是哪種類型。
Java Gson樹模型 API
樹模型API在內(nèi)存中創(chuàng)建JSON文檔的樹表示。它構(gòu)建JsonElements的樹。JsonElement是代表Json元素的類。它可以是JsonObject,JsonArray,JsonPrimitive或JsonNull。
Gson樹模型寫
在以下示例中,我們使用Gson樹模型API將Java對(duì)象寫入JSON。
GsonTreeModelWrite.java
package com.zetcode;
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Writer;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
class Car {
private final String name;
private final String model;
private final int price;
private final String[] colours;
public Car(String name, String model, int price, String[] colours) {
this.name = name;
this.model = model;
this.price = price;
this.colours = colours;
}
}
public class GsonTreeModelWrite {
public static void main(String[] args) throws FileNotFoundException, IOException {
List<Car> cars = new ArrayList<>();
cars.add(new Car("Audi", "2012", 22000,
new String[]{"gray", "red", "white"}));
cars.add(new Car("Skoda", "2016", 14000,
new String[]{"black", "gray", "white"}));
cars.add(new Car("Volvo", "2010", 19500,
new String[]{"black", "silver", "beige"}));
String fileName = "src/main/resources/cars.json";
Path path = Paths.get(fileName);
try (Writer writer = Files.newBufferedWriter(path, StandardCharsets.UTF_8)) {
Gson gson = new Gson();
JsonElement tree = gson.toJsonTree(cars);
gson.toJson(tree, writer);
}
System.out.println("Cars written to file");
}
}
汽車對(duì)象列表被序列化為JSON格式。
JsonElement tree = gson.toJsonTree(cars);
toJsonTree方法將指定的對(duì)象序列化為其等效表示形式,作為JsonElements的樹。
JsonArray jarray = tree.getAsJsonArray();
我們使用getAsJsonArray()方法將樹轉(zhuǎn)換為JsonArray。
JsonElement jel = jarray.get(1);
我們從數(shù)組中獲取第二個(gè)元素。
JsonObject object = jel.getAsJsonObject();
object.addProperty("model", "2009");
我們修改一個(gè)屬性。
gson.toJson(tree, writer);
最后,我們將樹對(duì)象寫入文件中。
Gson樹模型讀取
在以下示例中,我們使用Gson樹模型API從JSON讀取Java對(duì)象。
cars.json
[{"name":"Audi","model":"2012","price":22000,"colours":["gray","red","white"]},
{"name":"Skoda","model":"2009","price":14000,"colours":["black","gray","white"]},
{"name":"Volvo","model":"2010","price":19500,"colours":["black","silver","beige"]}]
這是cars.json文件中的JSON數(shù)據(jù)。
GsonTreeModelRead.java
package com.zetcode;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.Reader;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class GsonTreeModelRead {
public static void main(String[] args) throws FileNotFoundException, IOException {
String fileName = "src/main/resources/cars.json";
Path path = Paths.get(fileName);
try (Reader reader = Files.newBufferedReader(path,
StandardCharsets.UTF_8)) {
JsonParser parser = new JsonParser();
JsonElement tree = parser.parse(reader);
JsonArray array = tree.getAsJsonArray();
for (JsonElement element : array) {
if (element.isJsonObject()) {
JsonObject car = element.getAsJsonObject();
System.out.println("********************");
System.out.println(car.get("name").getAsString());
System.out.println(car.get("model").getAsString());
System.out.println(car.get("price").getAsInt());
JsonArray cols = car.getAsJsonArray("colors");
cols.forEach(col -> {
System.out.println(col);
});
}
}
}
}
}
在示例中,我們將JSON數(shù)據(jù)從文件讀取到JsonElements樹中。
JsonParser parser = new JsonParser();
JsonElement tree = parser.parse(reader);
JsonParser將JSON解析為JsonElements的樹結(jié)構(gòu)。
JsonArray array = tree.getAsJsonArray();
我們將樹作為JsonArray。
for (JsonElement element : array) {
if (element.isJsonObject()) {
JsonObject car = element.getAsJsonObject();
System.out.println("********************");
System.out.println(car.get("name").getAsString());
System.out.println(car.get("model").getAsString());
System.out.println(car.get("price").getAsInt());
JsonArray cols = car.getAsJsonArray("colors");
cols.forEach(col -> {
System.out.println(col);
});
}
}
我們?yōu)g覽JsonArray并打印其元素的內(nèi)容。
Java Gson流API
Gson流API是一個(gè)低級(jí)API,它以離散記號(hào)(JsonTokens)的形式讀取和寫入 JSON。 主要類別是JsonReader和JsonWriter。JsonToken是JSON編碼的字符串中的結(jié)構(gòu),名稱或值類型。
這些是JsonToken類型:
-
BEGIN_ARRAY— 打開(kāi)JSON數(shù)組 -
END_ARRAY— 關(guān)閉JSON數(shù)組 -
BEGIN_OBJECT— 打開(kāi)JSON對(duì)象 -
END_OBJECT— 關(guān)閉JSON對(duì)象 -
NAME-JSON屬性名稱 -
STRING—JSON字符串 -
NUMBER—JSON數(shù)字(雙精度,長(zhǎng)整型或整型) -
BOOLEAN—JSON布爾值 -
NULL—JSON空值 -
END_DOCUMENT—JSON流的末尾。
JsonWriter
JsonWriter將JSON編碼值寫入流,一次寫入一個(gè)記號(hào)。 流包含文字值(字符串,數(shù)字,布爾值和null)以及對(duì)象和數(shù)組的開(kāi)始和結(jié)束定界符。每個(gè)JSON文檔必須包含一個(gè)頂級(jí)數(shù)組或?qū)ο蟆?/p>
使用beginObject()和endObject()方法調(diào)用創(chuàng)建對(duì)象。在對(duì)象內(nèi),標(biāo)記在名稱及其值之間交替。 在beginArray()和endArray()方法調(diào)用中創(chuàng)建數(shù)組。
GsonStreamApiWrite.java
package com.zetcode;
import com.google.gson.stream.JsonWriter;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
public class GsonStreamApiWrite {
public static void main(String[] args) throws IOException {
String fileName = "src/main/resources/cars.json";
Path path = Paths.get(fileName);
try (JsonWriter writer = new JsonWriter(Files.newBufferedWriter(path,
StandardCharsets.UTF_8))) {
writer.beginObject();
writer.name("name").value("Audi");
writer.name("model").value("2012");
writer.name("price").value(22000);
writer.name("colours");
writer.beginArray();
writer.value("gray");
writer.value("red");
writer.value("white");
writer.endArray();
writer.endObject();
}
System.out.println("Data written to file");
}
}
在示例中,我們將一個(gè)汽車對(duì)象寫入JSON文件。
try (JsonWriter writer = new JsonWriter(Files.newBufferedWriter(path,
StandardCharsets.UTF_8))) {
創(chuàng)建一個(gè)新的JsonWriter。
writer.beginObject();
...
writer.endObject();
如上所述,每個(gè)JSON文檔必須具有一個(gè)頂級(jí)數(shù)組或?qū)ο蟆?在我們的例子中,我們有一個(gè)頂級(jí)對(duì)象。
writer.name("name").value("Audi");
writer.name("model").value("2012");
writer.name("price").value(22000);
我們將鍵值對(duì)寫入文檔。
writer.name("colours");
writer.beginArray();
writer.value("gray");
writer.value("red");
writer.value("white");
writer.endArray();
在這里,我們創(chuàng)建一個(gè)數(shù)組。
JsonReader
JsonReader讀取JSON編碼值作為記號(hào)流。
GsonStreamApiRead.java
package com.zetcode;
import com.google.gson.stream.JsonReader;
import com.google.gson.stream.JsonToken;
import java.io.IOException;
import java.io.StringReader;
public class GsonStreamApiRead {
public static void main(String[] args) throws IOException {
String json_string = "{\"name\":\"chair\",\"quantity\":3}";
try (JsonReader reader = new JsonReader(new StringReader(json_string))) {
while (reader.hasNext()) {
JsonToken nextToken = reader.peek();
if (JsonToken.BEGIN_OBJECT.equals(nextToken)) {
reader.beginObject();
} else if (JsonToken.NAME.equals(nextToken)) {
reader.nextName();
} else if (JsonToken.STRING.equals(nextToken)) {
String value = reader.nextString();
System.out.format("%s: ", value);
} else if (JsonToken.NUMBER.equals(nextToken)) {
long value = reader.nextLong();
System.out.println(value);
}
}
}
}
}
該示例使用JsonReader從JSON字符串讀取數(shù)據(jù)。
JsonReader reader = new JsonReader(new StringReader(json_string));
JsonReader對(duì)象已創(chuàng)建。它從JSON字符串讀取。
while (reader.hasNext()) {
在while循環(huán)中,我們迭代流中的記號(hào)。
JsonToken nextToken = reader.peek();
我們使用peek()方法獲得下一個(gè)標(biāo)記的類型。
reader.beginObject();
beginObject()方法使用JSON流中的下一個(gè)記號(hào),并斷言它是新對(duì)象的開(kāi)始。
reader.nextName();
nextName()方法返回下一個(gè)JsonToken并使用它。
String value = reader.nextString();
System.out.format("%s: ", value);
我們獲取下一個(gè)字符串值并將其打印到控制臺(tái)。
在本教程中,我們展示了如何通過(guò)Gson庫(kù)使用JSON。