将 JSON 对象发布到 Symfony 2 [英] Posting JSON objects to Symfony 2

查看:26
本文介绍了将 JSON 对象发布到 Symfony 2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 Symfony 2 开展一个项目,我构建了一个包来处理我所有的数据库服务,这些服务来回传递 JSON 数据.

I'm working on a project using Symfony 2, I've built a bundle to handle all my database services which passes JSON data back and forward.

我的问题/疑问:

  • 是否可以直接发布一个 JSON 对象?目前,我通过给对象一个名称来欺骗我的 ajax 调用的普通表单帖子 json={"key":"value"} 如果我不给它一个名字我不能似乎从 Symfony 请求对象中获取数据 $JSON = $request->request->get('json');

  • Is it possible to post a straight up JSON object? Currently I'm spoofing a normal form post for my ajax calls by giving the object a name json={"key":"value"} if I don't give it a name I can't seem to get the data from the Symfony request object $JSON = $request->request->get('json');

我希望能够使用一个服务包来处理来自 AJAX 调用或普通 Symfony 形式的数据.目前我正在提交提交的 Symfony 表单,获取数据然后使用 JSON_ENCODE,我只是不知道如何将数据发布到我的服务控制器,它需要请求数据.

I want to be able to use the one service bundle to handle both data coming from AJAX calls, or a normal Symfony form. Currently I'm taking the submitted Symfony form, getting the data then using JSON_ENCODE, I just can't work out how to post the data through to my services controller which is expecting request data.

总结:

  • 我希望 Symfony 接受 JSON 发布对象而不是表单.

  • I want Symfony to accept a JSON post object rather than a form.

我想使用请求/响应在控制器之间传递 JSON 对象

I want to pass the JSON object between controllers using Request/Response

如果我对这一切都做错了,请随时告诉我!

If I'm going about this all wrong, feel free to tell me so!

推荐答案

如果您想在控制器中检索作为标准 JSON 在请求正文中发送的数据,您可以执行类似于以下操作:

If you want to retrieve data in your controller that's been sent as standard JSON in the request body, you can do something similar to the following:

public function yourAction()
{
    $params = array();
    $content = $this->get("request")->getContent();
    if (!empty($content))
    {
        $params = json_decode($content, true); // 2nd param to get as array
    }
}

现在 $params 将是一个充满 JSON 数据的数组.删除 json_decode() 调用中的 true 参数值以获得 stdClass 对象.

Now $params will be an array full of your JSON data. Remove the true parameter value in the json_decode() call to get a stdClass object.

这篇关于将 JSON 对象发布到 Symfony 2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆