要讀取嵌套的JSON數(shù)據(jù),您可以通過遞歸的方式逐層讀取JSON對(duì)象中的嵌套數(shù)據(jù)。例如,假設(shè)您有以下嵌套的JSON數(shù)據(jù):
{
"name": "John Doe",
"age": 30,
"address": {
"street": "123 Main Street",
"city": "New York",
"country": "USA"
}
}
您可以使用JSONObject類來讀取嵌套的JSON數(shù)據(jù)。以下是一個(gè)示例代碼,演示如何讀取上述JSON數(shù)據(jù)中的嵌套數(shù)據(jù):
import org.json.JSONObject;
public class Main {
public static void main(String[] args) {
String jsonString = "{\"name\": \"John Doe\", \"age\": 30, \"address\": {\"street\": \"123 Main Street\", \"city\": \"New York\", \"country\": \"USA\"}}";
JSONObject jsonObject = new JSONObject(jsonString);
String name = jsonObject.getString("name");
int age = jsonObject.getInt("age");
JSONObject addressObject = jsonObject.getJSONObject("address");
String street = addressObject.getString("street");
String city = addressObject.getString("city");
String country = addressObject.getString("country");
System.out.println("Name: " + name);
System.out.println("Age: " + age);
System.out.println("Street: " + street);
System.out.println("City: " + city);
System.out.println("Country: " + country);
}
}
在上面的代碼中,我們首先將JSON字符串轉(zhuǎn)換為JSONObject對(duì)象,然后逐層讀取JSON數(shù)據(jù)中的嵌套數(shù)據(jù)。請(qǐng)注意,我們使用JSONObject類的getJSONObject()和getString()方法來獲取嵌套的JSON對(duì)象和字符串值。
通過遞歸的方式,您可以處理任意深度的嵌套JSON數(shù)據(jù)。