Symfony / FOSRestBundle: empty JSON response (using serializer containing symfony)

I am learning to create an API with symfony (using FOSRestBundle). I follow the French textbook. Obviously, at first I try to write the code myself, but even with copy / paste, it saves my empty JSON array when I make a GET request to the appropriate route (rest-api.local / places).

The code works fine if I "format" the code in a 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 a handler like 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 a JSON response, but have nothing between "{[], [], []}" (and I have 3 entries in my database):

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

    return $places;
}

This is my first post on stackoverflow, so I hope my question is clear. A good day.

+4
1

app/config/services.yml :

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

, , json .

+1

Source: https://habr.com/ru/post/1648662/


All Articles