Java 从JSON获取所有用户并将其放入TextView
我正在尝试在我的应用程序上解析这个Java 从JSON获取所有用户并将其放入TextView,java,android,Java,Android,我正在尝试在我的应用程序上解析这个JSON,并尝试将结果放在TextView上。从现在起,我将JSON放在字符串中,这是我的JSON [{ "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "Sincere@april.biz", "address": { "street": "Kulas Light", "suite": "Apt. 556",
JSON
,并尝试将结果放在TextView
上。从现在起,我将JSON
放在字符串中,这是我的JSON
[{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere@april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
我试过这个:
JSONArray users = new JSONArray(result);
tvNames.setText(users.get("name"));
但是它不起作用。您正在尝试从JSONArray
获取名称,您需要遍历它并找到带有键“name”的JSONObject,如下所示:
private String getAllNames(String result){
StringBuilder names = new StringBuilder();
try{
JSONArray users = new JSONArray(result);
for(int i = 0; i<users.length();i++){
JSONObject user = users.getJSONObject(i);
names.append(user.getString("name")).append("\n");
}
}catch(JSONException ex){
Log.d("Debug","Error parsing json " + ex.getMessage());
}
return names.toString();
}
tvNames.setText()