英文:
How can I return a list of 40 distinct objects when pulling only the userName value(s) from a JSONArray?
问题
在以下的getJsonUsername
方法中,我传入整个列表和一个空字符串。在这个方法内部,我遍历列表并提取"username"键。
我可以看到循环中以正确格式显示的40个用户名,例如{"username": "amyT"},{"username": "johnH"}等等。
请问我如何返回包含40个不同对象的列表?
listUsersJson = getUserInfo();
String users = "";
JSONArray listOfUserNames = getJsonUsername(listUsersJson, users);
在这段代码中,我只打印了列表中的最后一个用户名40次。如何返回包含40个不同对象的列表?
logger.info("************listOfUserNames************ " + listOfUserNames);
以下是getJsonUsername
方法的代码:
private JSONArray getJsonUsername(JSONArray listUsersJson, String users) throws JSONException {
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
for (int index = 0; index < listUsersJson.length(); ++index) {
JSONObject user = listUsersJson.getJSONObject(index);
userName = user.getString("userName");
jsonObject.put("userName", userName);
jsonArray.put(jsonObject);
}
return jsonArray;
}
英文:
I have a JSONArray in which I need to pull only the userName value(s) and then map those usernames
to key value pair {"username": "name"}. There are 40 names.
When I return I do get 40 items back but it is the last username in the list 40 times.
How do I return the list of 40 distinct objects?
In the below getJsonUsername method I pass the entire list and an empty string.
Within the method I loop over the list and pull the "username" key.
I can see all 40 usernames via debugger when looping in proper format {"username": "amyT"} {"username": "johnH"}...etc.
How do I return the list of 40 distinct objects?
listUsersJson = getUserInfo();
String users = "";
JSONArray listofUserNames = getJsonUsername(listUsersJson, users);
//Prints only the last userName from list 40 times.
logger.info("************listofUserNames************ " +
listofUserNames);
private JSONArray getJsonUsername(JSONArray listUsersJson,
String users ) throws JSONException {
JSONObject jsonObject = new JSONObject();
JSONArray jsonArray = new JSONArray();
for (int index = 0; index < listUsersJson.length(); ++index)
{
JSONObject users = listUsersJson.getJSONObject(index);
userName = users.getString("userName");
jsonObject.put("userName", userName);
jsonArray.put(jsonObject);
}
return jsonArray;
}
答案1
得分: 1
只创建一个JSONObject
,然后一次又一次地更新它,从而使它只包含最新的用户名。然后一次又一次地将其添加到JSONArray
中,所以最终的数组将只包含一个相同的对象一次又一次地重复。
将jsonObject
的创建移到循环内,在put
之前。
英文:
You only create one JSONObject
and you keep updating it over and over again which modifies it to have just the latest user name. And you add it to the JSONArray
over and over again, so the final array will have just one, identical object repeated over and over.
Move the creation of jsonObject
into the loop, right before the put
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论