【问题标题】:How can i parse json array?我如何解析 json 数组?
【发布时间】:2015-09-15 00:53:31
【问题描述】:

我正在构建一个 Android 应用程序,我需要使用来自我的 localhost 的一些数据填充自定义列表视图。我正在尝试使用 volley JsonArrayRequest 以 JSONObject 数组的格式获取该数据,但我得到的只是 org.json.JSONException: End of input at character 0 of。这是我的 json 数组请求:

final String URL = "http://10.0.3.2/androidapi/index.php";
        JsonArrayRequest productsReq = new JsonArrayRequest(Method.POST, URL, new Listener<JSONArray>() {

            @Override
            public void onResponse(JSONArray response) {
                Log.d("productTAG", response.toString());
                for(int i = 0; i < response.length(); i++)
                {
                    try 
                    {   
                        JSONObject productObj = response.getJSONObject(i);
                        String title = productObj.getString("title");
                        String description = productObj.getString("description");
                        String category = productObj.getString("category");
                        String subCategory = productObj.getString("subCategory");
                        String size = productObj.getString("size");
                        String price = productObj.getString("price");
                        String thumbnailUrl = productObj.getString("image_one");

                        Product product = new Product(title, thumbnailUrl, description, category, subCategory, size, price);
                        products.add(product);

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

            }
        }, new ErrorListener() {

            @Override
            public void onErrorResponse(VolleyError error) {
                Log.d("products_error", error.getMessage().toString());
                error.printStackTrace();
            }
        }){
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> params = new HashMap<String, String>();

                params.put("req", "products");
                params.put("category", category);
                params.put("subCategory", subCategory);

                return params;
            }
        };
        VolleyCore.getInstance(getActivity()).addToRequestQueue(productsReq); 

我使用的方法是POST,在getParams 下我添加了一个名为req 的标签,其值为products。我正在index.php 中检查这个标签。这是我查询表的函数:

public function getItems($category, $subCategory)
    {
        $query = mysql_query("SELECT * FROM items WHERE category = '$category' AND sub_category = '$subCategory'") or die(mysql_error());


        $objects = array();
        if($query)
        {
            while($objects = mysql_fetch_assoc($query))
            {
                $final[] = $objects;
            }
        }
        return $final;

    }

在 index.php 中,我正在检查请求:

if(isset($_POST['req']) && $_POST['req'] == 'products')
    {
        $category = $_POST['category'];
        $subCategory = $_POST['subCategory'];


        $obj = $func->getItems($category, $subCategory);

        echo json_encode($obj);

    }

$func 是类的实例化,我在其中保持所有方法与数据库一起工作(包括getItems())。如果我使用 volley StringRequest 我确实得到了回复,但是为什么我在使用 JsonArrayRequest 时没有得到回复?我做错了什么?
编辑
响应示例

06-28 15:05:58.750: D/productTAG(3853): 


[  
   {  
      "_id":"2",
      "user_email":"unemail",
      "title":"fsdfsd",
      "description":"dffdhfg",
      "pri‌​ce":"12",
      "quantity":"12",
      "size":"L",
      "category":"Men",
      "sub_category":"Shoes",
      "imag‌​e_one":"base 64 code…",
      "image_two":"base 64 code..",
      "image_three":"base 64 code"
   },
   {  
      "_id":"3",
      "user_email":"unemail",
      "title":"fsdfsd",
      "description":"dffdhfg‌​",
      "price":"12",
      "quantity":"12",
      "size":"L",
      "category":"Men",
      "sub_category":"Shoes"      ‌​,
      "image_one":"base 64 code",
      "image_two":"base 64 code",
      "image_three":"base 64 code "
   }
]


使用StringRequest

【问题讨论】:

  • 我没有要填充列表视图的 JSON 文件。这是唯一的出路吗?
  • 响应返回的Json长什么样子?
  • 06-28 15:05:58.750: D/productTAG(3853): [{"_id":"2","user_email":"unemail","title":"fsdfsd", "description":"dffdhfg","price":"12","quantity":"12","size":"L","category":"Men","sub_category":"Shoes","image_one ":"base 64 代码...","image_two":"base 64 代码..","image_three":"base 64 代码"},{"_id":"3","user_email":"unemail","标题":"fsdfsd","描述":"dffdhfg","价格":"12","数量":"12","尺码":"L","类别":"男士","sub_category" :"鞋子","image_one":"base 64 码","image_two":"base 64 码","image_three":"base 64 码"}]
  • @ffs 您应该使用 Json 编辑您的问题,而不是在评论中。

标签: php android arrays json


【解决方案1】:

我不知道如何使用JsonArrayRequest,所以我使用了我的问题中提到的StringRequest,并解析了这样的响应:

@Override
            public void onResponse(String response) {
//              Log.d("productTAG", response);
                try {
                    JSONArray myArray = new JSONArray(response);

                    for(int i = 0; i < myArray.length(); i++)
                    {
                        JSONObject jObj = myArray.getJSONObject(i);
                        String category = jObj.getString("category");
                        Log.d("category", category);

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


这对我有用,也感谢@Peter P 的帮助!

【讨论】:

    【解决方案2】:

    你应该试试这个

    @Override
    public void onResponse(String response) 
        try {
            JSONArray myArray = new JSONArray(response);
    
            for(int i = 0; i < myArray.length(); i++)
            {
                JSONObject jObj = myArray.getJSONObject(i);
                String category = jObj.getString("category");
                Log.d("category", category);
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }
    

    【讨论】:

    • 也许您可以编辑您的答案以改进代码格式,成为更好的答案
    • 为什么“试试这个??”一个好的答案总是会解释所做的事情以及为什么以这种方式完成,不仅是为了 OP,而且对于未来的访问者来说。重复接受答案的含义是什么!请添加一些描述以使其他人理解。快乐编码:)
    猜你喜欢
    • 2015-09-06
    • 1970-01-01
    • 2013-12-29
    • 2014-11-09
    • 1970-01-01
    • 2020-10-21
    • 1970-01-01
    • 2012-04-17
    • 1970-01-01
    相关资源
    最近更新 更多