Gson 是一个用于解析和生成 JSON 数据的 Java 库。要解析嵌套的 JSON 数据,你需要先定义与 JSON 结构相匹配的 Java 类,然后使用 Gson 将 JSON 字符串解析为 Java 对象。
以下是一个简单的示例,说明如何使用 Gson 解析嵌套的 JSON 数据:
{
"name": "John",
"age": 30,
"address": {
"street": "123 Main St",
"city": "New York",
"state": "NY",
"zip": "10001"
},
"phoneNumbers": [
{
"type": "home",
"number": "555-555-1234"
},
{
"type": "work",
"number": "555-555-5678"
}
]
}
public class Person {
private String name;
private int age;
private Address address;
private List<PhoneNumber> phoneNumbers;
// Getters and setters
}
public class Address {
private String street;
private String city;
private String state;
private String zip;
// Getters and setters
}
public class PhoneNumber {
private String type;
private String number;
// Getters and setters
}
import com.google.gson.Gson;
public class Main {
public static void main(String[] args) {
String json = "{\"name\":\"John\",\"age\":30,\"address\":{\"street\":\"123 Main St\",\"city\":\"New York\",\"state\":\"NY\",\"zip\":\"10001\"},\"phoneNumbers\":[{\"type\":\"home\",\"number\":\"555-555-1234\"},{\"type\":\"work\",\"number\":\"555-555-5678\"}]}";
Gson gson = new Gson();
Person person = gson.fromJson(json, Person.class);
System.out.println("Name: " + person.getName());
System.out.println("Age: " + person.getAge());
System.out.println("Street: " + person.getAddress().getStreet());
System.out.println("City: " + person.getAddress().getCity());
System.out.println("State: " + person.getAddress().getState());
System.out.println("Zip: " + person.getAddress().getZip());
System.out.println("Home Phone: " + person.getPhoneNumbers().get(0).getType() + ": " + person.getPhoneNumbers().get(0).getNumber());
System.out.println("Work Phone: " + person.getPhoneNumbers().get(1).getType() + ": " + person.getPhoneNumbers().get(1).getNumber());
}
}
这个示例将输出解析后的 Java 对象的属性值。注意,你需要将类名和属性名与 JSON 字符串中的名称匹配。