从JSON获取所有用户并将其放入TextView

时间:2018-05-08 06:32:50

标签: java android

我尝试在我的APP上解析此JSON并尝试将结果从{C}增加到TextViewJSON String ,这是我的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"));

但它没有用。

1 个答案:

答案 0 :(得分:5)

您正在尝试从QMessageBox获取该名称,并且您需要遍历它并找到带有“name”键的JSONArray,如下所示:

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();
    }