【问题标题】:Volley JSON request only returning first two valuesVolley JSON 请求仅返回前两个值
【发布时间】:2020-02-26 01:28:16
【问题描述】:

我托管了一个 json 文件 -> http://cipherads.co.in/api/bbps/billerinfo.php

我需要获取所有“billerId”字段。我正在使用 Volley 发出 GET 请求并遍历对象。但我面临一个问题,我的日志只显示前两个“billerId”值。我该如何解决这个问题?

    String urlJsonObj = "http://cipherads.co.in/api/bbps/billerinfo.php";

    private void makeJsonObjectRequest() {

    //showpDialog();

    JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.GET,
            urlJsonObj, null, new Response.Listener<JSONObject>() {

        @Override
        public void onResponse(JSONObject response) {
            //Log.d(TAG, response.toString());

            try {
                JSONArray biller = response.getJSONArray("biller");
                Log.d(TAG, biller.toString());

                // Loop through biller Array and find billerID
                for (int i = 0; i < response.length(); i++)
                {
                    JSONObject billerID = (JSONObject) biller.get(i);
                    String id = billerID.getString("billerId");
                    Log.d(TAG, id);


                }


                Toast.makeText(getApplicationContext(), biller.toString(), Toast.LENGTH_LONG).show();

            } catch (JSONException e) {
                e.printStackTrace();
                Toast.makeText(getApplicationContext(),
                        "Error: " + e.getMessage(),
                        Toast.LENGTH_LONG).show();
            }

        }
    }, new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError error) {
            VolleyLog.d(TAG, "Error: " + error.getMessage());
            Toast.makeText(getApplicationContext(),
                    error.getMessage(), Toast.LENGTH_SHORT).show();
        }
    });

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(jsonObjReq);
}

【问题讨论】:

    标签: android json android-volley


    【解决方案1】:

    改变你的循环条件

    for (int i = 0; i < response.length(); i++)
    

    for (int i = 0; i < biller.length(); i++)
    

    【讨论】:

    • 谢谢。那行得通。我能知道我做错了什么吗?
    • 我认为 Volley 没有问题。 Volley 和 Retrofit 它们在网络呼叫方面的工作方式不同。优先考虑与谁相处。
    【解决方案2】:

    我认为问题出在这里 for (int i = 0; i &lt; response.length(); i++)

    您正在检查 JSONobject 的大小,在您的情况下给出 2。 使用

    for (int i = 0; i < biller.length(); i++)
    

    改为遍历 JSONArray 的大小。

    编辑:注意到我添加此答案后已经发布了答案,因此决定将其保留在这里,以防您需要一些相关的解释。

    【讨论】:

    • 谢谢。那行得通。我知道我做错了什么吗?您还建议使用 Retrofit 代替 volley 吗?
    • 好吧,这就是我取消删除答案的原因,无论如何,在您的情况下,response 是接收到完整响应的 JSON 对象,对于 json 响应中的 2 个键,其长度为 2你会得到“responseCode”和“biller”。此 biller 是您需要的 JSONArray 值,因此在使用 for 循环时,您需要包含在对象内的“biller”数组的完整长度,而不是没有。响应对象本身的键。至于哪个更好,它基于check this perhaps 的简单意见。希望这是可以理解的
    • 谢谢。这解决了这个问题。我会通过链接。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    相关资源
    最近更新 更多