skip to Main Content

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


  1. You may need this: https://symfony.com/doc/current/components/serializer.html

    $myDtos = $this->deserializer->deserialize($jsonString, MyDto::class . '[]', 'json');
    

    In this code, the second parameter MyDto::class . '[]' specifies that you want to deserialize the JSON string into an array of MyDto objects.

    Login or Signup to reply.
  2. Since Symfony 7.1, there is a new argument on MapRequestPayload attribute which allows you to type hint your controller argument with array, and specify the DTOs you expect :

    public funtion index(#[MapRequestPayload(type: MyDto::class)] array $dtos) {
        ...
    }
    

    cf. https://github.com/symfony/symfony/commit/3f721434062045c1bad7849d1b412d07aa2b98e4

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search