[英]json response iteration android studio/retrofit
您可以使用 GSON 庫將userListAccounts轉換為 ArrayList ,從中您可以簡單地獲取每個元素的用戶名。
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
<version>2.8.5</version>
</dependency>
data class UserAccount(
val creationTime: Int,
val deletionTime: Int,
val owner: Owner,
val status: String, // I assume the Datatype is string
)
data class Owner(
val email: String,
val givenName: String,
val id: String,
val lastName: String,
val realm: String, // I assume the Datatype is string
val userName: String
)
class UserAccount {
Integer creationTime;
Integer deletionTime;
Owner owner;
String status;
public UserAccount(
Integer creationTime,
Integer deletionTime,
Owner owner,
String status
) {
this.creationTime = creationTime;
this.deletionTime = deletionTime;
this.owner = owner;
this.status = status;
}
}
class Owner {
String email;
String givenName;
String id;
String lastName;
String realm;
String userName;
public Owner(
String email,
String givenName,
String id,
String lastName,
String realm,
String userName
) {
this.email = email;
this.givenName = givenName;
this.id = id;
this.lastName = lastName;
this.realm = realm;
this.userName = userName;
}
}
val gson = Gson();
val userAccounts: ArrayList<UserAccount> = gson.fromJson(userListAccounts, UserAccount::class.java);
val usernameList = ArrayList<String>()
for (account in userAccounts)
usernameList.add(account.owner.username)
usernameList 將包含 JSON 響應中存在的所有用戶名。
在您提供的 JSON 層次結構照片中,根元素的名稱沒有出現,所以我在下面的腳本中假設它為“root_element”
JSONObject
。JSONObject
中有多個元素(在圖片中命名為 0、1、2..); 然后您可以使用getJSONArray()
方法獲取JSONArray
。JSONArray
從 (0, 1, 2...)JSONObject
,該元素在您的 JSON 結構照片中owner
。getString()
讀取此所有者的字符串String jsonResponse = ""; // Put the entire JSON response as a String
JSONObject root = new JSONObject(jsonResponse); // jsonResponse is the entire JSON string
JSONArray rootArray = root.getJSONArray("root_element"); // your root element is not show in your provided photo
for (int i = 0; i < rootArray.length(); i++) {
JSONObject element = rootArray.getJSONObject(i);
JSONObject owner = element.getJSONObject("owner");
String email = owner.getString("email");
String givenName = owner.getString("givenName");
String id = owner.getString("id");
String lastName = owner.getString("lastName");
String realm = owner.getString("realm");
String userName = owner.getString("userName");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.