Gson是Google提供的一個(gè)用于處理JSON數(shù)據(jù)的Java庫,它可以把JSON字符串與Java對(duì)象之間進(jìn)行互相轉(zhuǎn)換。
使用Gson解析JSON字符串的過程可以分為三步:
- 創(chuàng)建Gson對(duì)象
- 將JSON字符串轉(zhuǎn)換成Java對(duì)象
- 將Java對(duì)象轉(zhuǎn)換成JSON字符串
Gson gson = new Gson();
String jsonString = "{ \"name\": \"Tom\", \"age\": 18 }"; Person person = gson.fromJson(jsonString, Person.class);
Person person = new Person("Jerry", 20); String jsonString = gson.toJson(person);
其中,第二步的解析需要指定一個(gè)Java類,Gson會(huì)通過反射機(jī)制自動(dòng)將JSON字符串映射到該類的屬性中。
例如,對(duì)于下面的JSON字符串:
{ "name": "Alice", "age": 25, "address": { "city": "Beijing", "street": "123 Main St." }, "phoneNumbers": [ "123456789", "987654321" ] }
可以定義如下Java類:
public class Person { private String name; private int age; private Address address; private ListphoneNumbers; // getters and setters } public class Address { private String city; private String street; // getters and setters }
然后使用以下代碼解析:
String jsonString = "..."; // 上述JSON字符串 Person person = gson.fromJson(jsonString, Person.class);
這時(shí),person
對(duì)象的屬性值如下:
name
: "Alice"age
: 25address
: 包含city
和street
兩個(gè)屬性的Address
對(duì)象phoneNumbers
: 包含兩個(gè)元素的List
對(duì)象,分別為"123456789"和"987654321"