Gson是一個可用來將Java 物件轉換為 JSON# 表示形式的函式庫。它也可用於將 JSON 字串轉換為等效的 Java 物件。要使用的主要類別是Gson,我們可以透過呼叫new Gson()來建立它,而GsonBuilder類別可用於建立Gson實例。
我們可以透過先建立一個Person類別來轉換物件列表,然後將JSON 格式的 Person 物件列表。
import java.util.*; import java.util.stream.*; import com.google.gson.*; public class JSONConverterTest { public static void main( String[] args ) { Gson gson = new GsonBuilder().setPrettyPrinting().create(); List list = Stream.of(new Person("Raja", "Ramesh", 30, "9959984800"), new Person("Jai", "Dev", 25, "7702144400"), new Person("Adithya", "Sai", 21, "7013536200"), new Person("Chaitanya", "Sai", 28, "9656444150")) .collect(Collectors.toList()); System.out.println("Convert list of person objects to Json:"); String json = gson.toJson(list); // converts to json System.out.println(json); } } // Person class<strong> </strong>class Person { private String firstName, lastName, contact; private int age; public Person(String firstName, String lastName, int age, String contact) { this.firstName = firstName; this.lastName = lastName; this.age = age; this.contact = contact; } public String toString() { return "[" + firstName + " " + lastName + " " + age + " " +contact +"]"; } }
Convert list of person objects to Json: [ { "firstName": "Raja", "lastName": "Ramesh", "contact": "9959984800", "age": 30 }, { "firstName": "Jai", "lastName": "Dev", "contact": "7702144400", "age": 25 }, { "firstName": "Adithya", "lastName": "Sai", "contact": "7013536200", "age": 21 }, { "firstName": "Chaitanya", "lastName": "Sai", "contact": "9656444150", "age": 28 } ]
以上是在Java中使用Gson庫將物件列表轉換為JSON的詳細內容。更多資訊請關注PHP中文網其他相關文章!