5

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.

  • Which Serializer you are using? Normally Serializer have additional expose from entity level, like in [JMSSerializerBundle](http://jmsyst.com/libs/serializer/master/cookbook/exclusion_strategies) – Jeet Jul 26 '16 at 09:37

1 Answers1

1

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.

pepper
  • 1,732
  • 2
  • 17
  • 33