要解析復(fù)雜的Android JSON結(jié)構(gòu),您可以使用以下步驟:
implementation 'com.google.code.gson:gson:2.8.9'
{
"name": "John Doe",
"age": 30,
"address": {
"street": "123 Main St",
"city": "New York",
"state": "NY"
}
}
您需要創(chuàng)建兩個Java類:Person.java和Address.java。Person類將包含name和age屬性,而Address類將包含street、city和state屬性。
public class Person {
private String name;
private int age;
private Address address;
// getter and setter methods
}
public class Address {
private String street;
private String city;
private String state;
// getter and setter methods
}
fromJson()
方法將其轉(zhuǎn)換為Java對象。例如:import com.google.gson.Gson;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String jsonString = "{ \"name\": \"John Doe\", \"age\": 30, \"address\": { \"street\": \"123 Main St\", \"city\": \"New York\", \"state\": \"NY\" } }";
Gson gson = new Gson();
Person person = gson.fromJson(jsonString, Person.class);
// Use the 'person' object as needed
}
}
String name = person.getName();
int age = person.getAge();
String street = person.getAddress().getStreet();
String city = person.getAddress().getCity();
String state = person.getAddress().getState();
通過這種方式,您可以解析復(fù)雜的Android JSON結(jié)構(gòu)并將其轉(zhuǎn)換為Java對象,以便在應(yīng)用程序中使用。