2 Methods to Return Object as JSON Response in Symfony 7

2 Methods to Return Object as JSON Response in Symfony 7

JSON is a widely used data format for implementing APIs. Symfony framework provides the JsonResponse class which enables to represent an HTTP response in JSON format. However, this class works with array.

This tutorial provides example how to return object as JSON response in Symfony 7 application.

Let's say we have the User class which should be returned as JSON response:

src/Entity/User.php

<?php

namespace App\Entity;

class User
{
    private string $name;

    private int $age;

    public function getName(): string { return $this->name; }
    public function setName(string $name): void { $this->name = $name; }

    public function getAge(): int { return $this->age; }
    public function setAge(int $age): void { $this->age = $age; }
}

Method 1 - Custom factory class

We implemented a new class which allows to create HTTP response from a given object. Serializer component is used to convert object to JSON format. Response is created with corresponding Content-Type header. HTTP status code and additional headers can be provided as well.

src/Factory/JsonResponseFactory.php

<?php

namespace App\Factory;

use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\SerializerInterface;

class JsonResponseFactory
{
    public function __construct(private SerializerInterface $serializer)
    {
    }

    public function create(object $data, int $status = 200, array $headers = []): Response
    {
        return new Response(
            $this->serializer->serialize($data, JsonEncoder::FORMAT),
            $status,
            array_merge($headers, ['Content-Type' => 'application/json;charset=UTF-8'])
        );
    }
}

We can use a new class in controller as follows:

src/Controller/TestController.php

<?php

namespace App\Controller;

use App\Entity\User;
use App\Factory\JsonResponseFactory;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class TestController
{
    public function __construct(private JsonResponseFactory $jsonResponseFactory)
    {
    }

    #[Route('/')]
    public function index(): Response
    {
        $user = new User();
        $user->setName('John');
        $user->setAge(25);

        return $this->jsonResponseFactory->create($user);
    }
}

The response which will be returned to client:

{"name":"John","age":25}

Method 2 - Abstract controller

If controller already extends AbstractController provided by Symfony and no need additional features, the json method in an abstract class can be used to return an object as JSON response.

src/Controller/TestController.php

<?php

namespace App\Controller;

use App\Entity\User;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Attribute\Route;

class TestController extends AbstractController
{
    #[Route('/')]
    public function index(): Response
    {
        $user = new User();
        $user->setName('John');
        $user->setAge(25);

        return $this->json(
            $user,
            headers: ['Content-Type' => 'application/json;charset=UTF-8']
        );
    }
}

The 2 Comments Found

  1. Avatar
    tonte quilks Reply

    If you have your controller extend Symfony\Bundle\FrameworkBundle\Controller\AbstractController you could have simply used return $this->json($user);

Leave a Comment

Cancel reply

Your email address will not be published.