【问题标题】:how to convert a json to a php object in symfony2?如何在 symfony2 中将 json 转换为 php 对象?
【发布时间】:2011-11-13 16:42:15
【问题描述】:

通过 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 似乎为空


海报:

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

【问题讨论】:

  • 我猜你没有使用“json”作为这个 POST 参数的名称
  • 我根本没有主动使用任何名字,我会把上面的js贴出来......
  • 啊,所以我必须写数据:"data=" + $.toJSON({indices: newOrder}) 一切都很好。可能有更好的解决方案。
  • 您发送了一个 POST 请求,但您在正文中发送了 JSON,看看我的第三次编辑
  • +1 有趣的问题......那天早些时候我自己也在想这个问题

标签: php json symfony


【解决方案1】:

获取通过正文发送的数据:

$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)
  }
}

【讨论】:

  • 非常感谢!如果你能问对人,事情就会变得如此简单:)
  • Arrgh,但是我如何从请求中获取 json?
  • 我似乎仍然无法访问 json。我更新了我的问题以显示有问题的实际方法...
  • $json = json_decode($request->getContent(), true); - true 将您的 json 解码为数组而不是 stdObj
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-07-03
  • 1970-01-01
  • 1970-01-01
  • 2015-02-05
  • 1970-01-01
相关资源
最近更新 更多