在開發(fā)中,我們經(jīng)常需要將Java對(duì)象轉(zhuǎn)換成JSON對(duì)象。當(dāng)對(duì)象層次比較簡單時(shí),可以使用Jackson等庫輕松實(shí)現(xiàn)。但當(dāng)對(duì)象層次比較復(fù)雜時(shí),這些庫的轉(zhuǎn)換機(jī)制就顯得相對(duì)繁瑣,需要經(jīng)過多次轉(zhuǎn)換才能實(shí)現(xiàn)。Gson是一個(gè)在轉(zhuǎn)換多層Java對(duì)象到JSON對(duì)象時(shí)表現(xiàn)優(yōu)異的庫。
比如,我們有一個(gè)包含多層嵌套的Java對(duì)象:
class Person { String name; int age; Address address; } class Address { String street; String city; String state; String zip; } Person person = new Person(); person.name = "John"; person.age = 24; Address address = new Address(); address.street = "123 Main St"; address.city = "Anytown"; address.state = "CA"; address.zip = "12345"; person.address = address;
我們希望將這個(gè)Person對(duì)象轉(zhuǎn)換成JSON字符串。使用Gson庫,可以很容易地實(shí)現(xiàn):
Gson gson = new Gson(); String json = gson.toJson(person); System.out.println(json);
輸出結(jié)果如下:
{ "name": "John", "age": 24, "address": { "street": "123 Main St", "city": "Anytown", "state": "CA", "zip": "12345" } }
Gson將Java對(duì)象嵌套的屬性轉(zhuǎn)換成JSON對(duì)象的嵌套結(jié)構(gòu)。如果需要反向?qū)SON字符串轉(zhuǎn)換成Java對(duì)象,則使用Gson提供的fromJson()方法:
String json = "{\"name\":\"John\",\"age\":24,\"address\":{\"street\":\"123 Main St\",\"city\":\"Anytown\",\"state\":\"CA\",\"zip\":\"12345\"}}"; Person person = gson.fromJson(json, Person.class);
與ToJson()方法相反,fromJson()方法接受一個(gè)JSON字符串作為參數(shù),并將其轉(zhuǎn)換成Java對(duì)象。
總結(jié):Gson通過反射機(jī)制智能地將Java對(duì)象轉(zhuǎn)換成JSON對(duì)象,支持多層嵌套。使用Gson庫,可以方便地處理嵌套結(jié)構(gòu)復(fù)雜的Java對(duì)象。