我有一个嵌套了PointDto类(点数组)的OrderDto类:
class OrderDto
{
/**
* @var PointDto[]
* @Assert\All({
* @Assert\Type("App\Dto\PointDto")
* })
* @Assert\Valid()
*/
private array $points;
// getters, setters
}
PointDto类还使用验证器约束:
class PointDto
{
/**
* @Assert\NotBlank()
*/
private string $address;
// getters, setters
}
我的控制器:
/**
* @Rest\Post("/order/calc")
* @ParamConverter("orderDto", converter="fos_rest.request_body")
*/
public function calcOrder(OrderDto $orderDto, ConstraintViolationListInterface $validationErrors)
{
if (count($validationErrors) > 0)
return $this->json($validationErrors, Response::HTTP_BAD_REQUEST);
return ApiResponseUtil::okData(['sum' => 0]);
}
但当发送带有嵌套dto对象的请求时,如下所示:
{
"points": [
{
"address": "",
"person": {
"name": "",
"phone": ""
}
}
]
}
验证器无法确定类型,错误:
{
"error": "points[0]: This value should be of type App\\Dto\\PointDto.",
"violations": [
{
"property": "points[0]",
"message": "This value should be of type App\\Dto\\PointDto."
}
]
}
有没有办法反序列化嵌套的对象?
发布于 2021-07-03 20:59:28
我也遇到过类似的问题。
我不得不对字段使用@var注释,iterable作为它的类型,ArrayCollection作为初始化值。
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\ODM\MongoDB\Mapping\Annotations as ODM;
class OrderDto
{
/**
* @var PointDto[] - this annotation is super important
*
* @ODM\Field
* @Assert\All({
* @Assert\Type("App\Dto\PointDto")
* })
* @Assert\Valid()
*/
private iterable $points;
public function __construct()
{
$this->points = new ArrayCollection();
}
public function setPoints(iterable $points) // Don't use Collection type here, it will lead to a type error
{
$this->points = $points;
}
}
https://stackoverflow.com/questions/60410008
复制相似问题