如何在symfony2中将json转换为php对象?

Jan*_*Jan 6 php json symfony

通过jquery,我ajax/POST这个json

{"indices":[1,2,6]}:
Run Code Online (Sandbox Code Playgroud)

到symfony2动作.现在我只关心数组,所以如果这让事情变得相当容易,我也可以发帖[1,2,6].

如何将其转换为php对象?


不知何故,这不起作用:

/**
 * @Route("/admin/page/applySortIndex", name="page_applysortindex")
 * @Method("post")
 * @Template()
 */
public function applySortIndexAction()
{
    $request = $this->getRequest();
    $j = json_decode($request->request->get('json'));
    $indices = $j->indices;
    return array('data'=> $indices);
}
Run Code Online (Sandbox Code Playgroud)

给了一个

注意:尝试在.../PageController.php第64行中获取非对象的属性(500内部服务器错误)

这将是我访问$ j-> indices的地方,其中$ j似乎为null


海报:

$.ajax({
      type: 'POST',
      url: "{{ path('page_applysortindex')}}",
      data: $.toJSON({indices: newOrder}),
      success: ...
Run Code Online (Sandbox Code Playgroud)

Raf*_*ael 5

要获取通过身体使用发送的数据:

$request = $this->getRequest();
$request->getContent();
Run Code Online (Sandbox Code Playgroud)

检查输出然后采取行动.但这将包含json.

(是的,测试过它.这导致你的json)


从控制器中获取名为json的POST参数:

$request = $this->getRequest();
$request->request->get('json');
Run Code Online (Sandbox Code Playgroud)

申请对象


$j = json_decode('{"indices":[1,2,6]}');

var_dump($j);
Run Code Online (Sandbox Code Playgroud)

导致:

object(stdClass)#1 (1) {
  ["indices"]=>
  array(3) {
    [0]=>
    int(1)
    [1]=>
    int(2)
    [2]=>
    int(6)
  }
}
Run Code Online (Sandbox Code Playgroud)