Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Posting JSON objects to Symfony 2

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.

My Problem/Question:

  • 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');

  • 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.

To summarise:

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

  • 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!

like image 201
greg Avatar asked Mar 01 '12 18:03

greg


2 Answers

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

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.

like image 194
richsage Avatar answered Nov 10 '22 17:11

richsage


I wrote method to get content as array

protected function getContentAsArray(Request $request){
    $content = $request->getContent();

    if(empty($content)){
        throw new BadRequestHttpException("Content is empty");
    }

    if(!Validator::isValidJsonString($content)){
        throw new BadRequestHttpException("Content is not a valid json");
    }

    return new ArrayCollection(json_decode($content, true));
}

And I use this method as shown below

$content = $this->getContentAsArray($request);
$category = new Category();
$category->setTitle($content->get('title'));
$category->setMetaTitle($content->get('meta_title'));
like image 10
Farid Movsumov Avatar answered Nov 10 '22 18:11

Farid Movsumov