Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

symfony/FOSRestBundle : empty JSON response (using the symfony embodied serializer)

I'm learning to build API with symfony (using FOSRestBundle). I'm following a french tutorial. Obviously, I first try to write the code by myself but even with a copy/paste, it keeps get me empty JSON array when I do a GET request to the appropriate route (rest-api.local/places).

The code works OK if I "format" the code in php array:

  public function getPlacesAction(Request $request)
{
    $places = $this->get('doctrine.orm.entity_manager')
            ->getRepository('AppBundle:Place')
            ->findAll();
    /* @var $places Place[] */

    $formatted = [];
    foreach ($places as $place) {
        $formatted[] = [
           'id' => $place->getId(),
           'name' => $place->getName(),
           'address' => $place->getAddress(),
        ];
    }

    return new JsonResponse($formatted);
}

but then I try to serialize directly $places, using the view handler of fost Rest (in config.yml)

fos_rest:
routing_loader:
    include_format: false
view:
    view_response_listener: true
format_listener:
    rules:
        - { path: '^/', priorities: ['json'], fallback_format: 'json' }

and changing my function in my controller to the following code, I get my JSON response but without anything between "{ [],[],[]}" (and I do have 3 entries in my DB):

 public function getPlacesAction(Request $request)
{
    $places = $this->get('doctrine.orm.entity_manager')
            ->getRepository('AppBundle:Place')
            ->findAll();
    /* @var $places Place[] */

    return $places;
}

It's my first post on stackoverflow, so I hope my question is clear, Have a nice day.

like image 563
damioune123 Avatar asked Nov 08 '22 12:11

damioune123


1 Answers

In my app/config/services.yml I've added this:

services:
    object_normalizer:
        class: Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer
        # Important! Tag this service or it wouldn't work
        tags:
            - { name: serializer.normalizer }

I still can't get why it works but all of a sudden I've got a nice json in response.

like image 60
pepper Avatar answered Nov 14 '22 21:11

pepper