Skip to content

Cannot JSON encode null #62404

@Bilge

Description

@Bilge

Symfony version(s) affected

7.3.7

Description

It should be trivially possible to call return $this->json(null) in a controller, however the result of this varies depending whether the serializer service is present. If it is, the output is null, as expected. However, if it is not, the result is {}, and moreover, there is no clear way to "trick" it into somehow outputting null, since internally null is replaced with ArrayObject which explains why we get {} output instead.

How to reproduce

#[Route('/foo')]
final class Foo extends AbstractController
{
    #[Route(methods: ['GET'])]
    public function get(): Response
    {
        return $this->json(null);
    }
}

Possible Solution

The behaviour is normalized by installing the serializer component, but this should not be necessary to get sane behaviour.

Edit: actually it is possible to trick it by doing the following:

    public function get(): Response
    {
        $json = null;

        return $json ? $this->json($json) : new JsonResponse('null', json: true);
    }

This is definitely not an intuitive pattern, though.

Additional Context

No response

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions