我正在尝试解析JSON数组并将其添加到我的适配器类。
我的代码:
String url = "https://api.github.com/users";
JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
try {
JSONArray results = response.getJSONArray(); // error in this line since there is no array name
for(int i = 0;i < results.length();i++){
JSONObject result = results.getJSONObject(i);
String name = result.getString("login");
users.add(new User(name.substring(0,1).toUpperCase() + name.substring(1),result.getString("avatar_url")));
}
// notify that data has changed in recyclerview
notifyDataSetChanged();
} catch (JSONException e) {
e.printStackTrace();
Log.e("cs50", "Json error", e);
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Log.e("cs50","Github User List error",error);
}
});
[您可以看到我正在尝试从Github API URL获得响应,但是由于没有数组名,但是我的代码需要一个参数,因此我收到了错误消息。我该如何解析?
更改此行
JSONArray results = response.getJSONArray(); // error in this line since there is no array name
收件人
JSONArray results = new JSONArray(response); // error in this line since there is no array name
如果在响应JSONArray中不返回,将创建一个异常,请稍后处理。