Android - Volley错误回复

Moh*_*din 0 android json android-volley

尝试解析listview中的JSON数据时,我的凌空抛出错误响应.是因为我的JSON数据在对象节点中,而不是数组节点.

JSON数据

{
    "users": [{
        "userId": 1,
        "name": "Dya Vega",
        "profilePhoto": "https://graph.facebook.com/1301454197/picture?type=large",
        "dateMatched": "1/1/2015",
        "distance": "1 miles away",
        "status": "Online",
        "requestMessage": "Hi, can I know you?",
        "like": 234,
        "lastActive": "Active 1 hour ago"
    }, {
        "userId": 2,
        "name": "Esa Ezzatinor",
        "profilePhoto": "https://graph.facebook.com/1269334432/picture?type=large",
        "dateMatched": "1/1/2015",
        "distance": "2 miles away",
        "status": "Online",
        "requestMessage": "Hi, can I know you?",
        "like": 234,
        "lastActive": "Active 2 hour ago"
    }]
}
Run Code Online (Sandbox Code Playgroud)

// Creating volley request obj
        JsonArrayRequest userReq = new JsonArrayRequest(url,
                new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                        Log.d(TAG, response.toString());
                        hidePDialog();

                        // Parsing json
                        for (int i = 0; i < response.length(); i++) {
                            try {

                                JSONObject obj = response.getJSONObject(i);
                                User user = new User();
                                user.setName(obj.getString("name"));
                                user.setProfilePhotoUrl(obj.getString("profilePicture"));
                                user.setLastActive(obj.getString("lastLogin"));

                                // adding movie to movies array
                                userList.add(user);

                            } catch (JSONException e) {
                                e.printStackTrace();
                            }

                        }

                        // notifying list adapter about data changes
                        // so that it renders the list view with updated data
                        adapter.notifyDataSetChanged();
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {
                        VolleyLog.d(TAG, "Error: " + error.getMessage());
                        hidePDialog();

                    }
                });
Run Code Online (Sandbox Code Playgroud)

请指教.谢谢.

ρяσ*_*я K 5

注意:

=> 如果string包含{第一个字符,则string包含JSONObject作为根容器

=> 如果string包含[第一个字符,则string包含JSONArray作为根容器

发布的json字符串包含JSONObject作为root而不是JSONArray.使用JsonObjectRequest而不是JsonArrayRequest使用Volley向服务器发出请求