Android JSON 排球

Android JSON VOlley

美好的一天,我想从 this url 获取数据,我在 onResponse 方法实现方面遇到问题:

我有这样的东西:

 public void onClick(View v) {
                JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://horoscope-api.herokuapp.com/",

                        new Response.Listener<JSONObject>() {
                            @Override
                            public void onResponse(JSONObject response) {
                                try {
//The Problem is here
                                    JSONArray jsonArray = response.getJSONArray("");
                                    String author = jsonArray.getString(0);
                                    textView.setText(author);

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

                        new Response.ErrorListener() {
                            @Override
                            public void onErrorResponse(VolleyError error) {

                            }
                        }


                );
                requestQueue.add(jsonObjectRequest);
            }

我不明白如何正确实现 onResponse 方法,我知道我必须从数组或对象中获取字符串,但是来自 link 的数据让我难以理解它是对象还是数组,你能告诉我如何从此 url 获取作者字段吗? 谢谢

因为你的link中的response是JSONObject,你只需要在onResponse里面做如下:

String author = response.getString("author");
textView.setText(author);

希望对您有所帮助!

您得到的响应不是 JSONArray,而是 JSONObject。你可以试试下面的代码,看看能不能找到作者。

public void onClick(View v) {
            JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(Request.Method.GET, "http://horoscope-api.herokuapp.com/",

                    new Response.Listener<JSONObject>() {
                        @Override
                        public void onResponse(JSONObject response) {
                            try {
                                String author = response.get("author");
                                textView.setText(author);

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

                    new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {

                        }
                    }


            );
            requestQueue.add(jsonObjectRequest);
        }

希望对您有所帮助。

来自 link 的数据是 JSONObject 而不是 JSONArray。调用 response.getString("author"); 获取作者字符串。

try{
    String author = response.getString("author");
} catch(JSONException e) {
    e.printStackTrace();
}