getting JSONArrays with Volley

﹥>﹥吖頭↗ 提交于 2019-12-20 04:33:31

问题


I am trying to get a JSONArray from a server but getting all kinds of errors. EDIT : tried adding all these imports.

    import android.support.v7.app.AppCompatActivity;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.Response.Listener;
import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.toolbox.JsonArrayRequest;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.android.volley.Response.ErrorListener;


    public class VolleyFetcher extends AppCompatActivity
    {
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = "https://xxxxxx.json"; 

        JsonObjectRequest jsObjRequest = new JsonObjectRequest(
                Request.Method.GET, url, null, new Response.Listener<JSONArray>() {
                    @Override
                    public void onResponse(JSONArray response) {
                    // TODO Auto-generated method stub
                }
                }, new Response.ErrorListener() {

                @Override
                public void onErrorResponse(VolleyError error) 
                {
                    // TODO Auto-generated method stub
                }
                });

        queue.add(jsObjRequest);    
    }

My errors:

Response cannot be resolved to a type

JSONArray cannot be resolved to a type

Syntax error on token "jsObjRequest", VariableDeclaratorId expected after this token (//line : queue.add(jsObjRequest)

Any advice would be very much appreciated.


回答1:


JSONObjectRequest should be used if the result returned is a JSON Object.

If you're expecting to get a JSON Array back, you should use JSONArrayRequest. This request should be included in Volley's toolbox package.

The result request declaration should look like this:

JsonArrayRequest request = new JsonArrayRequest("http://my.url.com/", new Response.Listener<JSONArray>()
        {
            @Override
            public void onResponse(JSONArray response)
            {

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

            }
        });


来源:https://stackoverflow.com/questions/31365888/getting-jsonarrays-with-volley

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!