【问题标题】:android, php, parsing JSON in php file sent from androidandroid,php,解析从android发送的php文件中的JSON
【发布时间】:2013-08-29 10:51:20
【问题描述】:

我有这个 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);
?>

但是$count$num 总是返回null,请大家帮忙,谢谢。

【问题讨论】:

  • 您确定$josn 有任何价值吗?你能告诉我们输出吗?
  • 是的,它返回{\\\"count\\\":\\\"2\\\",\\\"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},{\\\"id\\\":\\\"a_a\\\",\\\"amount\\\":56,\\\"duration\\\":\\\"0:12\\\",\\\"time\\\":1234566,\\\"type\\\":2}]}
  • 那么$json_data 输出什么?
  • 我知道它有点混乱抱歉,当我尝试stripslashes($_REQUEST['jsonarray']) 我有{\"count\":\"2\",\"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},{\"id\":\"a_a\",\"amount\":56,\"duration\":\"0:12\",\"time\":1234566,\"type\":2}]}
  • 运行 stripslashes 两次。

标签: php http-post json


【解决方案1】:
$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);

【讨论】:

  • 非常感谢@JimL,我的问题是我对php不太熟悉,并且在php中使用数组或对象,但知道我知道如何从json中获取数组或单个对象,非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多