要解析復雜的Android JSON結構,您可以使用以下步驟:
implementation 'com.google.code.gson:gson:2.8.9'
{
"name": "John Doe",
"age": 30,
"address": {
"street": "123 Main St",
"city": "New York",
"state": "NY"
}
}
您需要創建兩個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()
方法將其轉換為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();
通過這種方式,您可以解析復雜的Android JSON結構并將其轉換為Java對象,以便在應用程序中使用。