[英]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.