-2

我有这个 JSON

{
   "count":"3",
   "num":"1",
   "array":[
      {
         "id":"a_a",
         "amount":56,
         "duration":"0:12",
         "time":1234566,
         "type":0
      },
      {
         "id":"a_a",
         "amount":56,
         "duration":"0:12",
         "time":1234566,
         "type":1
      }
   ]
}

在android中创建并发送**HttpPost**

,我尝试了很多方法来获取 php 中的数据,我的 php 文件是这样的:

<?php
    $response = array();
//$json_data = json_encode(stripslashes($_POST['jsonarray']))

    $josn = file_get_contents("php://input");
    $json_data = json_decode($josn,true);

    $count = $json_data->{'count'};
    $num = $json_data["num"];

     $response["data"]=$count;
     $response["data2"]=$num;
        // echoing JSON response
        echo json_encode($response);
?>

但是总是返回null $count$num请提供任何帮助,谢谢。

4

1 回答 1

0
$json_data = json_decode($josn,true);

这将返回一个数组,而不是一个对象(稍后将在代码中使用)。使用它将 json 字符串转换为对象:

$json_data = json_decode($josn);

或者您可以只使用数组,在这种情况下,您的代码应如下所示:

<?php
$response = array();
//$json_data = json_encode(stripslashes($_POST['jsonarray']))

$josn = file_get_contents("php://input");
$json_data = json_decode($josn, true); // using true to get array

$count = $json_data["count"]; // accessing array values as normal
$num = $json_data["num"]; // accessing array values as normal

$response["data"] = $count; // instead of setting $count first you could just add
$response["data2"] = $num; // the json_data array values directly to the response array

// echoing JSON response
echo json_encode($response);
于 2013-08-29T11:03:31.193 回答