使用JSONArray和Volley进行POST请求

时间:2016-01-14 11:56:43

标签: php android json android-volley

我正在使用Volley发送一个帖子请求,并以JSON数组的形式接收响应。如果帖子是成功的,这将是JSON响应。

   [{
    "memID": "",
    "OrderDate": "2016-01-02 18:32:12",
    "orderid": "14",
    "memberID": "0",
    "user_number": "770689504",
    "data_bundle": "",
    "network": "o2",
    "data_number": "77055552",
    "amount": "7",
    "status": "Pending",
    "payment_mtd": "Paypal"
}

json Exception说:

[{
    "memID": "",
    "OrderDate": "2016-01-02 18:32:12",
    "orderid": "14",
    "memberID": "0",
    "user_number": "770689504",
    "data_bundle": "",
    "network": "o2",
    "data_number": "77055552",
    "amount": "7",
    "status": "Pending",
    "payment_mtd": "Paypal"
}
org.json.JSONArray类型的

无法转换为JSONObject。

CODE:

  // Volley's json array request object
    CustomJsonRequest req = new CustomJsonRequest(Request.Method.POST, ORDER_STATS, null,
            new Response.Listener<JSONArray>() {
                @Override
                public void onResponse(JSONArray response) {
                    Log.d(TAG, response.toString());

                    if (response.length() > 0) {

                        // looping through json and adding to list
                        for (int i = 0; i < response.length(); i++) {
                            try {
                                JSONObject orderObj = response.getJSONObject(i);

                                int or_id = orderObj.getInt("orderid");
                                String or_date = orderObj.getString("OrderDate");
                                String or_data = orderObj.getString("data_bundle");
                                String or_amount = orderObj.getString("amount");
                                String or_number = orderObj.getString("data_number");
                                String or_payment = orderObj.getString("payment_mtd");
                                String or_status = orderObj.getString("status");

                                OrderDetail m = new OrderDetail(or_id, or_date, or_data, or_amount, or_number, or_payment, or_status);

                                orderDetailList.add(0, m);


                            } catch (JSONException e) {
                                Log.e(TAG, "JSON Parsing error: " + e.getMessage());
                            }
                        }

                        adapter.notifyDataSetChanged();
                    }

                    // stopping swipe refresh
                    swipeRefreshLayout.setRefreshing(false);

                }
            }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Log.e(TAG, "Server Error: " + error.getMessage());

            Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_LONG).show();

            // stopping swipe refresh
            swipeRefreshLayout.setRefreshing(false);
        }
    });


    // Adding request to request queue
    MyApplication.getInstance().addToRequestQueue(req);
}

public class CustomJsonRequest extends Request {
    String gMobile = savedSharedPreference.getString("mobile", "Not found");

    Map<String, String> params;
    private Response.Listener listener;

    public CustomJsonRequest(int requestMethod, String url, Map<String, String> params,
                             Response.Listener responseListener, Response.ErrorListener errorListener) {

        super(requestMethod, url, errorListener);


        params = new HashMap<String, String>();
        params.put("mobile", gMobile);
        this.params = params;
        this.listener = responseListener;
    }

    @Override
    protected void deliverResponse(Object response) {
        listener.onResponse(response);

    }

    @Override
    public Map<String, String> getParams() throws AuthFailureError {

        return params;
    }

    @Override
    protected Response parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data, HttpHeaderParser.parseCharset(response.headers));
            return Response.success(new JSONObject(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }

}

PHP边码

<?php

 if($_SERVER['REQUEST_METHOD']=='POST'){

 $mobile = $_POST['mobile'];

  require_once('dbConnect.php');

 // query the application data
$sql = "SELECT * FROM order_details WHERE user_number = '$mobile'";
$result = mysqli_query($con, $sql);

// an array to save the application data
$rows = array();

// iterate to query result and add every rows into array
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
    $rows[] = $row;
}

// close the database connection
mysqli_close($con);

// echo the application data in json format
echo json_encode($rows);

}
?>

这可以很好地发送POST参数。我不知道我做错了什么。

1 个答案:

答案 0 :(得分:0)

由于您要发送单个对象(并且您的java希望收到单个对象,而不是数组,根据异常消息),您只需编码第一个sql结果行:

$sql = "SELECT * FROM order_details WHERE user_number = '$mobile'";
$result = mysqli_query($con, $sql);

// no need for an array to save the application data - its just one result
//$rows = array();

// no need to iterate to query result and add every rows into array, see above
//while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
//    $rows[] = $row;
//}
//just get 1st row
$row = mysqli_fetch_array($result, MYSQLI_ASSOC)

// close the database connection
mysqli_close($con);
//set a proper header
header('Content-Type: application/json');
//note, $row, not $rows
echo json_encode($row);