【发布时间】:2020-04-22 20:25:33
【问题描述】:
这可能非常简单,但我是新手,在 android studio 中做这件事。这个 JSON 解析让我大吃一惊。基本上我只需要这个数组中 userName 的值。我能够得到我需要遍历每个“所有者”并获取用户名并将其放入列表的响应。我不知道如何获取 userName 字段。用户名可以包含@,也可以不包含。任何帮助是极大的赞赏!
【问题讨论】:
这可能非常简单,但我是新手,在 android studio 中做这件事。这个 JSON 解析让我大吃一惊。基本上我只需要这个数组中 userName 的值。我能够得到我需要遍历每个“所有者”并获取用户名并将其放入列表的响应。我不知道如何获取 userName 字段。用户名可以包含@,也可以不包含。任何帮助是极大的赞赏!
【问题讨论】:
在您提供的 JSON 层次结构照片中,根元素的名称没有出现,所以我在下面的脚本中假设它为“root_element”
JSONObject。JSONObject 有多个元素(如图
命名为 0, 1, 2..);然后你可以得到一个JSONArray 使用
getJSONArray() 方法。JSONArray 以从 (0, 1, 2...) 中获取特定元素owner 这个特定元素创建另一个 JSONObject。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");
}
【讨论】:
您可以使用 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 响应中存在的所有用户名。
【讨论】:
for (Account userListAccount : userList.getAccounts()) Log.i("Access", "UserNames from json;" +userListAccount.getOwner().getUserName()); 及其记录用户名...但不确定如何在对话框或 toast 列表中实际使用它。 2020-04-22 19:28:52.638 18757-18757/com.test.myandroid I/Access: UserNames from json;tester@bla.com