我有 2 个 DTO 对象,我需要将 json 转换为它:
class SomeDTO
{
public function __construct(
#[SerializedName('some_property')]
private string $someProperty,
#[SerializedName('some_other_property')]
private int $someOtherProperty,
) {
}
public function getSomeProperty(): string
{
return $this->someProperty;
}
public function setSomeProperty(string $someProperty): self
{
$this->someProperty = $someProperty;
return $this;
}
public function getSomeOtherProperty(): int
{
return $this->someOtherProperty;
}
public function setSomeOtherProperty(int $someOtherProperty): self
{
$this->someOtherProperty = $someOtherProperty;
return $this;
}
}
和
class ArrDTO
{
/**
* @param SomeDTO[] $arr
*/
public function __construct(
private array $arr
) {
}
/**
* @return SomeDTO[]
*/
public function getArr(): array
{
return $this->arr;
}
/**
* @param SomeDTO[] $arr
* @return $this
*/
public function setArr(array $arr): self
{
$this->arr = $arr;
return $this;
}
}
因此 ArrDTO::$arr 属性是 SomeDTO 对象的数组。 我有这样的 json,其结构与 ArrDTO 相同:
$json = '{"arr":[{"some_property":"str","some_other_property":1},{"some_property":"str2","some_other_property":2}]}';
目标 - 使用 Serializer 将此 $json 转换为 ArrDTO。 这段代码
use Symfony\Component\Serializer\SerializerInterface;
...
$arrDTO = $serializer->deserialize($json, ArrDTO::class, 'json');
给我一个 ArrDTO,但在 $this->arr 属性中使用 array[] (数组的数组)而不是 SomeDTO[] (SomeDTO 的数组)。有没有办法用序列化器来实现它?
在“上层”类中使用 DiscriminatorMap
#[DiscriminatorMap(typeProperty: 'type', mapping: [
'arr' => SomeDTO::class,
])]
class ArrDTO
{
// ...
}