使用json_decode()获取null

时间:2014-09-28 04:36:09

标签: php cakephp

我尝试在此CakePHP函数中通过ID解码JSON更新记录:

public function update() {
    $this->layout = 'ajax';
    if($this->request->is('post')) {
        $decoded = json_decode($this->request->data,true);
        if($data = $this->Foobar->save($decoded)) {
            $data = json_encode(array(
                "message" => "Foobar successfully updated.",
                "update" => $this->request->data
            ));
        } else {
            $data = json_encode(array(
                "message" => "Foobar could not be updated.",
                "update" => $decoded,
                "updateJson" => $this->request->data
            ));
        }
    } else {
        $data = json_encode(array(
            "message" => "Method should be post."
        ));
    }
    $this->set('data', $data);

但是解码会一直返回null

{"message":"Foobar could not be updated.","update":null,"updateJson":{"ID":"1","status":2}}

但是,如果我转到http://www.compileonline.com/execute_php_online.php并输入:

<html><head></head><body>
<pre>
<?php
   print_r(json_decode('{"ID":"1","status":2}', true));
?>
</pre>
</body></html>

它运作得很好......

查看相关问题......

  • 我已经看到了尝试json_last_error()的建议,这会为我返回0
  • 我看到有人提到magic_quotes可能会开启,我已经关闭了。
  • 我已经看到了使用json_decode(utf8_encode($this->request->data),true);的建议,这仍然会为我返回null

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我认为您不应该对JSON解码数据。

尝试直接保存:

$data = $this->Foobar->save($this->request->data);