【发布时间】:2021-12-23 22:29:06
【问题描述】:
参加以下 DTO 课程:
class UserDTO {
/**
* @param AddressDTO[] $addressBook
*/
public function __construct(
public string $name,
public int $age,
public ?AddressDTO $billingAddress,
public ?AddressDTO $shippingAddress,
public array $addressBook,
) {
}
}
class AddressDTO {
public function __construct(
public string $street,
public string $city,
) {
}
}
我想对 JSON 进行序列化和反序列化。
我正在使用以下序列化程序配置:
$encoders = [new JsonEncoder()];
$extractor = new PropertyInfoExtractor([], [
new PhpDocExtractor(),
new ReflectionExtractor(),
]);
$normalizers = [
new ObjectNormalizer(null, null, null, $extractor),
new ArrayDenormalizer(),
];
$serializer = new Serializer($normalizers, $encoders);
但是当序列化/反序列化这个对象时:
$address = new AddressDTO('Rue Paradis', 'Marseille');
$user = new UserDTO('John', 25, $address, null, [$address]);
$jsonContent = $serializer->serialize($user, 'json');
dd($serializer->deserialize($jsonContent, UserDTO::class, 'json'));
我得到以下结果:
UserDTO^ {#54
+name: "John"
+age: 25
+billingAddress: AddressDTO^ {#48
+street: "Rue Paradis"
+city: "Marseille"
}
+shippingAddress: null
+addressBook: array:1 [
0 => array:2 [
"street" => "Rue Paradis"
"city" => "Marseille"
]
]
}
当我期望时:
UserDTO^ {#54
+name: "John"
+age: 25
+billingAddress: AddressDTO^ {#48
+street: "Rue Paradis"
+city: "Marseille"
}
+shippingAddress: null
+addressBook: array:1 [
0 => AddressDTO^ {#48
+street: "Rue Paradis"
+city: "Marseille"
}
]
}
如您所见,$addressBook 被反序列化为array 的数组,而不是AddressDTO 的数组。 我希望 PhpDocExtractor 从构造函数中读取 @param AddressDTO[],但这不起作用。
仅当我将 $addressBook 设为使用 @var 记录的公共属性时才有效。
有没有办法让它在构造函数上使用简单的@param?
(非)工作演示:https://phpsandbox.io/n/gentle-mountain-mmod-rnmqd
我读过和尝试过的:
- Extract types of constructor parameters from docblock comment
- symfony deserialize nested objects
- How can I deserialize an array of objects in Symfony Serializer?
建议的解决方案似乎都不适合我。
【问题讨论】:
-
看起来不错。你在一个只注入 serializerInterface 的 symfony 应用程序中尝试过吗?
-
@alessandro_podo 我正在独立使用它。如果你想摆弄它,我在我的问题中添加了一个 phpsandbox.io 链接。
标签: symfony serialization symfony5