Gson 是一個(gè)用于將 Java 對(duì)象轉(zhuǎn)換為 JSON 字符串以及將 JSON 字符串解析為 Java 對(duì)象的庫(kù)。要處理嵌套對(duì)象,您只需按照以下步驟操作:
pom.xml
文件中添加以下依賴項(xiàng):<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.9</version>
</dependency>
public class Address {
private String street;
private String city;
// getters and setters
}
public class User {
private String name;
private int age;
private Address address;
// getters and setters
}
import com.google.gson.Gson;
public class Main {
public static void main(String[] args) {
// 創(chuàng)建一個(gè)嵌套對(duì)象
Address address = new Address();
address.setStreet("123 Main St");
address.setCity("New York");
User user = new User();
user.setName("John Doe");
user.setAge(30);
user.setAddress(address);
// 使用 Gson 將 Java 對(duì)象轉(zhuǎn)換為 JSON 字符串
Gson gson = new Gson();
String jsonString = gson.toJson(user);
System.out.println("JSON string: " + jsonString);
// 使用 Gson 將 JSON 字符串解析為 Java 對(duì)象
User parsedUser = gson.fromJson(jsonString, User.class);
System.out.println("Parsed user: " + parsedUser);
}
}
這將輸出以下內(nèi)容:
JSON string: {"address":{"street":"123 Main St","city":"New York"},"age":30,"name":"John Doe"}
Parsed user: John Doe@15db9742
如您所見(jiàn),Gson 成功地將嵌套對(duì)象轉(zhuǎn)換為 JSON 字符串,然后再將其解析回 Java 對(duì)象。