PHP Symfony parse JSON response deserialize class constructor
To parse and deserialize a JSON response using PHP Symfony, you can utilize the JsonResponse
class and the JsonDecoder
component. Here's a step-by-step guide on how to do it:
- First, ensure you have the
symfony/serializer
package installed. You can add it to yourcomposer.json
file:
{
"require": {
"symfony/serializer-bundle": "^5.4"
}
}
Then, run composer install
.
- Create a class that represents the JSON structure you want to deserialize. For example, let's assume you have the following JSON response:
{
"data": {
"name": "John Doe",
"age": 30,
"city": "New York"
}
}
Create a new file named User.php
in a new directory called src/App/Entity
:
namespace App\Entity;
class User
{
private $data;
public function __construct(array $data)
{
$this->data = $data;
}
public function getName(): string
{
return $this->data['name'];
}
public function getAge(): int
{
return $this->data['age'];
}
public function getCity(): string
{
return $this->data['city'];
}
}
- In your controller, create a method to handle the JSON response and deserialize it:
namespace App\Controller;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;
class JsonController extends AbstractController
{
public function getUserAction(Request $request)
{
$jsonResponse = new JsonResponse();
$decoder = new JsonDecoder();
$serializer = new Serializer([new ObjectNormalizer()], [new JsonEncoder()]);
$content = $request->getContent();
$userData = $decoder->decode($content, 'json');
$user = $serializer->deserialize($userData, User::class);
$jsonResponse->setData($user);
return $jsonResponse;
}
}
- Finally, create a route for the controller action:
# src/Route/route.yaml
json:
path: /json
methods: [GET]
controller: App\Controller\JsonController::getUserAction
Now, when you make a request to /json
with a JSON payload, the controller will deserialize it and return a User
object.