在cakephp中访问json请求数据

时间:2015-07-16 06:24:03

标签: php json cakephp

我从Gitlab收到以下Payload。

{
  "object_kind": "push",
  "before": "95790bf891e76fee5e1747ab589903a6a1f80f22",
  "after": "da1560886d4f094c3e6c9ef40349f7d38b5d27d7",
  "ref": "refs/heads/master",
  "user_id": 4,
  "user_name": "John Smith",
  "user_email": "john@example.com",
  "project_id": 15,
  "repository": {
    "name": "Diaspora",
    "url": "git@example.com:mike/diasporadiaspora.git",
    "description": "",
    "homepage": "http://example.com/mike/diaspora", 
    "git_http_url":"http://example.com/mike/diaspora.git",
    "git_ssh_url":"git@example.com:mike/diaspora.git",
    "visibility_level":0
  },
  "total_commits_count": 4
} 

在我的cakephp函数中,我正在访问它:

   public function push() {
          $data = $this->request->data;
          $branch = $data['ref'];
          $gitSshUrl = $data['repository']['git_ssh_url'];
   }

我能成功获取'ref'字段,但不能获取repository.git_ssh_url字段。

1 个答案:

答案 0 :(得分:0)

您收到的有效负载是JSON(使用this检查)。

您需要json_decode来解码JSON字符串。

public function push() {
   $data = $this->request->data('Post.title');
   $data_array = json_decode($data,true);
   $branch = $data_array['ref'];
   $gitSshUrl = $data_array['repository']['git_ssh_url'];
}

使用Cake,您还可以执行类似

的操作
$data = $this->request->input('json_decode');    
// Gets JSON encoded data submitted to a PUT/POST action