我正在尝试获取JSON数据并使用Volley库将其用于android应用程序,但即使我找不到我的代码中的错误,它也无法正常工作

时间:2018-06-21 02:19:06

标签: android json android-volley

//在这里,我们从setOnClickListener方法调用方法jsoneParse

private void jsonParse(){

///我在这里插入了我的网址

    String url = "https://api.myjson.com/bins/hrtn6";   

// json对象请求

    final JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {

            try {

//这是我们解析json对象的重要位置                     JSONArray jsonArray = response.getJSONArray(“ students”);

                for(int i = 0; i < jsonArray.length();i++){
                    JSONObject student = jsonArray.getJSONObject(i);
                    String firstname = student.getString("firstname");
                    String lastname = student.getString("lastname");
                    int age = student.getInt("age");


                    detailsText.append(firstname+" "+lastname+" "+String.valueOf(age)+"\n");
                }
            } 

//这些都是错误处理

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

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            error.printStackTrace();
        }
    });

///在这里,我们将请求插入请求队列

    mQueue.add(request);
}

3 个答案:

答案 0 :(得分:0)

只需将您的request method更改为get

final JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
.
.
.

答案 1 :(得分:0)

更改此

 final JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, null, new Response.Listener<JSONObject>() {

为此:

final JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {

答案 2 :(得分:0)

使您的requestbody字符串而不是null (网址后面的参数)

final JsonObjectRequest request = new JsonObjectRequest(Request.Method.POST, url, "", new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                .....
            }

     }

这对我有帮助, 也许这会帮助您, 快乐的编码