gson是一個(gè)用于Java語言的輕量級JSON處理庫。它可以將Java對象轉(zhuǎn)換成對應(yīng)的JSON格式,也可以將JSON格式的數(shù)據(jù)轉(zhuǎn)換成Java對象。
在處理復(fù)雜類(即包含嵌套和集合類型的類)時(shí),我們可以使用gson來方便地將Java對象轉(zhuǎn)換成JSON格式。
public class Person { private String name; private int age; private Listhobbies; private Map address; private Car car; // getters and setters } public class Car { private String brand; private String model; // getters and setters } public class Test { public static void main(String[] args) { Person person = new Person(); person.setName("Alice"); person.setAge(20); List hobbies = new ArrayList<>(); hobbies.add("reading"); hobbies.add("music"); person.setHobbies(hobbies); Map address = new HashMap<>(); address.put("city", "Beijing"); address.put("street", "Main Street"); person.setAddress(address); Car car = new Car(); car.setBrand("Toyota"); car.setModel("Camry"); person.setCar(car); Gson gson = new Gson(); String json = gson.toJson(person); System.out.println(json); } }
以上代碼定義了一個(gè)Person類,包含姓名、年齡、愛好(列表類型)、地址(映射類型)和汽車(嵌套類型)等屬性。在Test類中創(chuàng)建了一個(gè)Person對象,將其轉(zhuǎn)換成JSON格式并輸出。
運(yùn)行Test類,輸出結(jié)果如下:
{ "name":"Alice", "age":20, "hobbies":[ "reading", "music" ], "address":{ "city":"Beijing", "street":"Main Street" }, "car":{ "brand":"Toyota", "model":"Camry" } }
可以看出,使用gson將復(fù)雜類轉(zhuǎn)換成JSON格式非常方便,只需調(diào)用Gson類的toJson方法即可。