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

时间:2011-09-09 10:40:12

标签: php json symfony

通过jquery,我ajax / POST这个json

{"indices":[1,2,6]}:

到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);
}

给出

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

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


海报:

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

1 个答案:

答案 0 :(得分:5)

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

$request = $this->getRequest();
$request->getContent();

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

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


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

$request = $this->getRequest();
$request->request->get('json');

Request-object


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

var_dump($j);

导致:

object(stdClass)#1 (1) {
  ["indices"]=>
  array(3) {
    [0]=>
    int(1)
    [1]=>
    int(2)
    [2]=>
    int(6)
  }
}
相关问题