Strong Like Bull
Strong Like Bull

Reputation: 11297

Unable to return json in symfony 2

This is my controller

public function index2Action($name)
    {   
  $em = $this->getDoctrine()->getEntityManager();
  $test = $em->getRepository('RestWebServiceBundle:Test')->findall();
  return new Response(json_encode(array('locations' => $test)));

    }

When I go to the URL I get:

{"locations":[{}]}

However when I use:

public function index2Action($name)
    {   
$name ="Adam";
  return new Response(json_encode(array('locations' => $name)));

    }

I get the JSON.

What am I doing wrong? I am trying to get JSON in the first scenario.

UPDATE: I have verified that the $test variable is indeed not empty and when I do a print_r on it, it shows me the following:

Array
(
    [0] => Rest\WebServiceBundle\Entity\Test Object
        (
            [id:protected] => 1
            [title:protected] => test title
            [author:protected] => test author
            [blog:protected] => this is the blog
            [tags:protected] => 
            [comments:protected] => 
            [created:protected] => DateTime Object
                (
                    [date] => 2012-05-13 00:00:00
                    [timezone_type] => 3
                    [timezone] => America/Chicago
                )

            [updated:protected] => DateTime Object
                (
                    [date] => 2012-05-13 00:00:00
                    [timezone_type] => 3
                    [timezone] => America/Chicago
                )

        )

)
null

Upvotes: 0

Views: 1489

Answers (4)

Dixit Bhojani
Dixit Bhojani

Reputation: 66

When you have tried with $name it was worked because it is simple string value which is assigned to array. so json_encode can easily convert it.

But findall() method will return Test entity object so you can't convert it directly to Json using json_encode.

from entity object you can get data through getter & setter methods.

so If your Test entity data is not to much big then you can simply map your entity object data in array like below:

public function index2Action($name)
{   
    $em = $this->getDoctrine()->getEntityManager();
    $tests = $em->getRepository('RestWebServiceBundle:Test')->findAll();

    // Map the Test entities object into an associative array
    $testArray = [];
    foreach ($tests as $test) {
        $testArray[] = [
            'id' => $test->getId(),
            'title' => $test->getTitle(), 
            'author' => $test->getAuthor(),
            ... Add necessary fields data ...
        ];
    }

    return new Response(json_encode(['locations' => $testArray]));
}

Also you can simply use JsonResponse() method to return data in json format instead of Response with json_encode().

return new JsonResponse(['locations' => $testArray]);

With JsonResponse you don't need to manually encode your data using json_encode() method.

Upvotes: 0

Van Peterson
Van Peterson

Reputation: 91

I've tried this by using getArrayResult() instead of getResult() in my repository class & it works

Upvotes: 0

Remy Mellet
Remy Mellet

Reputation: 1795

        $obj = $test;

        $serializer = new Serializer(
            array(new GetSetMethodNormalizer()),
            array('json' => new JsonEncoder())
        );
        $json = $serializer->serialize($obj, 'json');

        $response = new \Symfony\Component\HttpFoundation\Response($json);
        $response->headers->set('Content-Type', 'application/json');
        return $response;

Upvotes: 0

Flask
Flask

Reputation: 4996

I would highly recommend you to use the serializer for return entities. have a look at the serializer component or the jmsserializerbundle.

Upvotes: 2

Related Questions