I’m working with Symfony and have an incoming JSON payload that looks like this:
[
{
"number": 1,
"description": "Test 1"
},
{
"number": 2,
"description": "Test 2"
},
{
"number": 3,
"description": "Test 3"
}
]
I have a Data Transfer Object (DTO) defined like this:
<?php
class MyDto {
public function __constructor(
public readonly int $number,
public readonly int $description,
) {}
}
My goal is to map the array of JSON objects directly to an array of MyDto objects in my Symfony controller. Here’s my current controller method:
public funtion index(#[MapRequestPayload] MyDto $dto) {
...
}
I’m trying to find a way to map the array of JSON objects to an array of MyDto objects without needing to create another DTO to wrap this data under a key. Is there a built-in or efficient way to do this in Symfony?
2
Answers
You may need this: https://symfony.com/doc/current/components/serializer.html
In this code, the second parameter
MyDto::class . '[]'
specifies that you want to deserialize the JSON string into an array ofMyDto
objects.Since Symfony 7.1, there is a new argument on
MapRequestPayload
attribute which allows you to type hint your controller argument witharray
, and specify the DTOs you expect :cf. https://github.com/symfony/symfony/commit/3f721434062045c1bad7849d1b412d07aa2b98e4