如何解码来自android json post volley的php中的json

时间:2016-01-27 00:26:22

标签: php android json

对不起我糟糕的英语和编程新手。我正在尝试解码从android volley JSON POST抛出的JSONObject。现在我能够从Android收到来自服务器的响应,我可以通过TOAST确认。我的问题是如何使用PHP从服务器端正确解码JSON。此JSON数据将用于在MySQL中插入新数据。我只是不知道正确的方法,并很难找到解码设置的答案。请你在这里给出任何建议。

public void testOrder (ArrayList<String> order_id,
                                      ArrayList<String> uname,
                                      ArrayList<String> prod_name,
                                      ArrayList<String> prod_id,
                                      ArrayList<String> quantity,
                                      ArrayList<String> branches,
                                      ArrayList<String> totalPrice,
                                      int itemIteration){
        JSONObject obj = null;
        JSONArray jsonArray = new JSONArray();
        final JSONObject finalobject = new JSONObject();
        for (int i = 0; i < itemIteration; i++) {
            obj = new JSONObject();
            Log.d("OBJECT_COUNTER", String.valueOf(i));
            try {
                obj.put("order_id",  order_id.get(i));
                Log.d("ORDER_ID",    order_id.get(i));
                obj.put("uname",     uname.get(i));
                Log.d("USERNAME",    uname.get(i));
                obj.put("prod_name", prod_name.get(i));
                Log.d("PROD_NAME",   prod_name.get(i));
                obj.put("quantity",  quantity.get(i));
                Log.d("PROD_QUANT",  quantity.get(i));
                obj.put("branch",    branches.get(i));
                Log.d("PROD_BRANCHES", branches.get(i));
                obj.put("totalPrice",  totalPrice.get(i));
                Log.d("TOTAL_PRICE",   totalPrice.get(i));
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            jsonArray.put(obj);
        }
            try {
                finalobject.put("ORDER_LIST", jsonArray);
                test = jsonArray.toString();
//                Toast.makeText(this,test,Toast.LENGTH_SHORT).show();
            } catch (JSONException e) {
                e.printStackTrace();
            }

        StringRequest strRequest = new StringRequest(Request.Method.POST, Config.TRY_JSON_POST,
                new Response.Listener<String>()
                {
                    @Override

                    public void onResponse(String response)
                    {
                        Toast.makeText(PlaceOrder.this, response, Toast.LENGTH_SHORT).show();
//                       
                    }
                },
                new Response.ErrorListener()
                {
                    @Override
                    public void onErrorResponse(VolleyError error)
                    {
                        Toast.makeText(PlaceOrder.this, error.toString(), Toast.LENGTH_SHORT).show();
                    }
                })
        {
            @Override
            protected Map<String, String> getParams()
            {
                Map<String, String> params = new HashMap<>();
                params.put("tag", finalobject.toString());
//                String obj = finalobject.toString();
//                Toast.makeText(PlaceOrder.this,obj,Toast.LENGTH_SHORT).show();
                return params;
            }
        };
        AppController.getmInstance().addToRequesQueue(strRequest);
    }
}

PHP代码

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

$response = array("ORDERLIST" => $_POST["tag"]);
//$response = array($_POST["tag"]);
//$my_array = json_decode($response,true);

echo json_encode(str_replace('\"','"',$response));

     echo "RECEIVED";

} else{

       echo "nothing";
}

我使用Log.d作为回复:

D /回复:

{"ORDERLIST":"{\"ORDER_LIST\":[{\"order_id\":\"1755\",\"uname\":\"jordan\",\"prod_name\":\"ABC\",\"quantity\":\"1\",\"branch\":\"Dapitan\",\"totalPrice\":\"23500\"},{\"order_id\":\"1755\",\"uname\":\"jordan\",\"prod_name\":\"AMD Kaveri A4-7300 APU HD8470D 2-Core 2GB 500GB CPU Package\",\"quantity\":\"1\",\"branch\":\"Dapitan\",\"totalPrice\":\"23500\"}]}"}

使用echo $ content后,这会显示在我的吐司上

D/Response: DATA:tag=%7B%22ORDER_LIST%22%3A%5B%7B%22order_id%22%3A%221755%22%2C%22uname%22%3A%22jordan%22%2C%22prod_name%22%3A%22ABC%22%2C%22quantity%22%3A%221%22%2C%22branch%22%3A%22Dapitan%22%2C%22totalPrice%22%3A%2223500%22%7D%2C%7B%22order_id%22%3A%221755%22%2C%22uname%22%3A%22jordan%22%2C%22prod_name%22%3A%22AMD+Kaveri+A4-7300+APU+HD8470D+2Core+2GB+500GB+CPU+Package%22%2C%22quantity%22%3A%221%22%2C%22branch%22%3A%22Dapitan%22%2C%22totalPrice%22%3A%2223500%22%7D%5D%7D&

编辑的PHP代码

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

$content   = file_get_contents( "php://input" );
$response  = json_decode($content,TRUE);
$orderlist = json_decode($response['ORDER_LIST'], TRUE);

//echo $orderlist[0][order_id][0];

echo "DATA: ";

foreach($orderlist AS $row ){
  echo $row[uname];
} 

      echo $response;
} else{
      echo "nothing";
}

1 个答案:

答案 0 :(得分:1)

(编辑)的

试试这个:

$content   = file_get_contents( "php://input" );
$response  = json_decode( $content, TRUE );
$orderlist = json_decode( $response['ORDERLIST'], TRUE );

从PHP文档:

  

php:// input是一个只读流,允许您从请求正文中读取原始数据。在POST请求的情况下,最好使用php:// input而不是$ HTTP_RAW_POST_DATA,因为它不依赖于特殊的php.ini指令。

解码json数据后,在$orderlist中获得一个关联数组。您现在可以选择将您喜欢的数组值保存到数据库中。

所以(即):$orderlist[0][order_id]$orderlist[1][uname]