这是我的控制器代码,用于接收带有JSON体的POST请求,然后我想将其反序列化到我的dto中。听起来很简单,但由于某些原因,没有达到预期的效果。其中一个属性是对象数组,当反序列化时,它被反序列化成数组的数组
主计长:
<?php
namespace App\Controller;
use Symfony\Component\Serializer\SerializerInterface;
use App\Dto\CreateDto;
class EntryController extends AbstractController
{
public function __construct(SerializerInterface $serializer)
{
$this->serializer = $serializer;
}
/**
* @Route("", methods={"POST"})
*
*/
public function createEntry(Request $request)
{
$content = $request->getContent();
$entry = $this->serializer->deserialize($content, CreateDto::class, 'json');
...
}
}
DTO:
<?php
namespace App\Dto;
class CreateDto
{
public $name;
public $email;
public $items; // this is CreateDto[]
}
我使用postman POST请求,body内容类型为json。
{ "name": "Example", "email": "example@example", "items": [ { "name": "sub", "email": "[email protected]" } ] }
Symfony 5.0.8版本
你需要声明哪些字段是seriliaze或deseriliaze。
<?php
namespace App\Dto;
use Symfony\Component\Serializer\Annotation\Groups;
class CreateDto
{
/**
* @Groups({"api""})
*/
public $name;
/**
* @Groups({"api""})
*/
public $email;
/**
* @Groups({"api""})
*/
public $items; // this is CreateDto[]
}
然后
$entry = $this->serializer->deserialize($content, CreateDto::class, 'json', ["groups" => "api"]);
给哪些组序列化或反序列化的序列化器。像这样。