1. 簡介
JSON 是一種流行的用於在服務器和客户端之間傳輸數據的互換數據格式。然而,在許多情況下,我們可能需要將 JSON 數組轉換為 Java 中的 List 對象以便進行進一步的處理或數據操作。
在本教程中,我們將比較使用 Java 中兩個流行的 JSON 庫(Gson 和 Jackson)來實現此轉換的不同方法。
2. 使用 Gson 庫
Gson 是一款廣泛使用的 JSON 庫,用於將 Java 對象序列化和反序列化為 JSON。它提供了一種簡單的方法,可以將 JSON 數組轉換為 List 對象。
2.1. Gson Maven 依賴
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.11.0</version>
</dependency>2.2. 將 JSON 數組轉換為 Java 列表
本節將討論如何使用 Gson 將 JSON 數組轉換為 Java 列表。
讓我們考慮一個 JSON 數組的示例:
[
{\"id\":1,\"name\":\"Icecream\",\"description\":\"Sweet and cold\"},
{\"id\":2,\"name\":\"Apple\",\"description\":\"Red and sweet\"},
{\"id\":3,\"name\":\"Carrot\",\"description\":\"Good for eyes\"}
];上述JSON數組代表一個產品類別的列表:
public class Product {
private int id;
private String name;
private String description;
public Product(int id, String name, String description) {
this.id = id;
this.name = name;
this.description = description;
}
// getter and setter
}現在我們有了 JSON 數組,讓我們嘗試理解它如何轉換為 List:
@Test
public void whenUsingGsonLibrary_thenCompareTwoProducts() {
Gson gson = new Gson();
Type listType = new TypeToken<List<Product>>() {}.getType();
List<Product> gsonList = gson.fromJson(jsonArray, listType);
Assert.assertEquals(1, gsonList.get(0).getId());
Assert.assertEquals("Sweet and cold", gsonList.get(0).getDescription());
Assert.assertEquals("Icecream", gsonList.get(0).getName());
}首先,我們需要創建 Gson 類的實例,它提供了 JSON 序列化和反序列化的方法。
我們可以使用 TypeToken 類指定目標 List 的類型。在上面的示例中,我們定義了目標類型為 List<Product>。
然後,我們使用 Gson 對象的 fromJson() 方法將 JSON 數組 String 轉換為 List。
由於我們已經將 JSON 數組轉換為 List,我們也可以嘗試分析斷言。在斷言中,我們比較 JSON 數組中某個字段(例如 ID 或 description)與轉換後的 gsonList,該 gsonList 代表 Product 類的 List。3. 使用 Jackson 庫
Jackson 是另一個廣泛使用的 Java JSON 庫。 在本節中,我們將討論如何使用 Jackson 庫將 JSON 數組轉換為 List。
3.1. Jackson Maven 依賴
我們需要將以下 Jackson 庫添加到項目依賴中:庫。
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.15.2</version>
</dependency>3.2. 將 JSON 數組轉換為 Java List
在本節中,我們將討論如何使用 Jackson 將 JSON 數組轉換為 List。
@Test
public void whenUsingJacksonLibrary_thenCompareTwoProducts() throws JsonProcessingException {
// The jsonArray is the same JSON array from the above example
ObjectMapper objectMapper = new ObjectMapper();
TypeReference<List<Product>> jacksonTypeReference = new TypeReference<List<Product>>() {};
List<Product> jacksonList = objectMapper.readValue(jsonArray, jacksonTypeReference);
Assert.assertEquals(1, jacksonList.get(0).getId());
Assert.assertEquals("Sweet and cold", jacksonList.get(0).getDescription());
Assert.assertEquals("Icecream", jacksonList.get(0).getName());
}我們創建了 ObjectMapper 類的實例,該類是 Jackson 庫中用於數據操作的核心類。
我們可以使用 TypeReference 類指定目標 List 的類型。 在上面的示例中,我們定義了目標類型為 List<Product>。
然後,我們使用 ObjectMapper 對象的 readValue() 方法將 JSON 數組 String 轉換為 List。
類似於之前討論的斷言,最後,我們比較 JSON 數組中的特定字段與 jacksonList 對應字段進行比較。
4. 結論
在本文中,我們探討了如何使用 Gson 和 Jackson 兩個流行的庫將 JSON 數組轉換為 Java List 的方法。
Gson 提供了一種簡單直接的方法,而 Jackson 則提供高級功能和高性能。Gson 與 Jackson 的選擇取決於特定項目的需求和偏好。