我正在嘗試反序列化為具有屬性的物件,該物件可能將一組物件作為值或為null.
我反序列化陣列沒有問題,但我需要將 null 反序列化為空陣列或 null 本身。
例如 { "items": null }
class A {
/**
* @var null|Item[]
*/
private $items = [];
/**
* @return Item[]|null
*/
public function getItems(): ?array
{
return $this->items ?? [];
}
/**
* @param Item $param
* @return A
*/
public function addItem(Item $param)
{
if (!is_array($this->items)) $this->items = [];
if (!in_array($param, $this->items))
$this->items[] = $param;
return $this;
}
// /** tried with this as well
// * @param array|null $param
// * @return A
// */
// public function setItems(?array $param)
// {
// $this->items = $param ?? [];
// return $this;
// }
/**
* @param Item $item
* @return A
*/
public function removeItem(Item $item): A
{
if (!is_array($this->items)) $this->items = [];
if (in_array($item, $this->items))
unset($this->items[array_search($item, $this->items)]);
return $this;
}
/**
* @param Item $item
* @return bool
*/
public function hasItem(Item $item): bool
{
return in_array($item, $this->items);
}
}
序列化程式看起來像這樣
$defaultContext = [
AbstractNormalizer::CIRCULAR_REFERENCE_HANDLER =>
function ($articles, $format, $context) {
return $articles->getId();
},
AbstractObjectNormalizer::SKIP_NULL_VALUES => false
];
$classMetadataFactory = new ClassMetadataFactory(new AnnotationLoader(new AnnotationReader()));
$metadataAwareNameConverter = new MetadataAwareNameConverter($classMetadataFactory);
$encoders = [new JsonEncoder()];
$serializer = new Serializer([
new ArrayDenormalizer(),
new DateTimeNormalizer(),
new ObjectNormalizer($classMetadataFactory, $metadataAwareNameConverter, null,
new ReflectionExtractor(), null, null, $defaultContext
),
], $encoders);
$a = $serializer->deserialize('{ "items": null }', A::class, 'json');
我得到的錯誤items是 null
[Symfony\Component\Serializer\Exception\InvalidArgumentException]
Data expected to be an array, null given.
是否可以擁有可為空的屬性?
uj5u.com熱心網友回復:
追蹤到 Serializer 源代碼,發現了三個可能的選項來擁有一個可為空的陣列。
選項1
Remove addItem, hasItem,removeItem方法,它允許設定空值、陣列等。在我的情況下,這是不太受歡迎的解決方案。
選項 2
添加建構式也有幫助。https://github.com/symfony/serializer/blob/5.3/Normalizer/AbstractNormalizer.php#L381
/**
* A constructor.
* @param array|null $items
*/
public function __construct($items)
{
$this->items = $items ?? [];
}
選項 3
處理空值的擴展ArrayDenormalizer和覆寫denormalize方法
public function denormalize($data, string $type, string $format = null, array $context = []): array
{
if (null === $this->denormalizer) {
throw new BadMethodCallException('Please set a denormalizer before calling denormalize()!');
}
if (!\is_array($data) && !is_null($data)) {
throw new InvalidArgumentException('Data expected to be an array or null, ' . get_debug_type($data) . ' given.');
}
if (!str_ends_with($type, '[]')) {
throw new InvalidArgumentException('Unsupported class: ' . $type);
}
if(is_null($data))
return [];
$type = substr($type, 0, -2);
$builtinType = isset($context['key_type']) ? $context['key_type']->getBuiltinType() : null;
foreach ($data as $key => $value) {
if (null !== $builtinType && !('is_' . $builtinType)($key)) {
throw new NotNormalizableValueException(sprintf('The type of the key "%s" must be "%s" ("%s" given).', $key, $builtinType, get_debug_type($key)));
}
$data[$key] = $this->denormalizer->denormalize($value, $type, $format, $context);
}
return $data;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/368141.html
上一篇:是否可以在Symfony5bundle中選擇Doctrine物體/資料庫表?
下一篇:從選單中查找我所在的專案路線
