Answer the question
In order to leave comments, you need to log in
How to solve error when deserializing an object with an array?
The following error occurs when deserializing an object:
Symfony\Component\Serializer\Exception\NotNormalizableValueException
The type of the "products" attribute for class "shop\manage\flexbe\objects\Lead" must be one of "shop\manage\flexbe\objects\Product[]" ("array "given).
{
"id": "9757241",
"time": "1567105530",
// другие параметры
"products": [
{
"title": "Product name",
"count": 1
}
]
}
private $products = [];
/**
* @return Product[]
*/
public function getProducts()
{
return $this->products;
}
/**
* @param Product $product
*/
public function addProduct(Product $product): void
{
$this->products[] = $product;
}
$normalizer = new ObjectNormalizer(null, null, new PropertyAccessor(), new ReflectionExtractor());
$serializer = new Serializer(array($normalizer), array(new JsonEncoder()));
$lead = $serializer->deserialize($data, Lead::class, 'json');
Answer the question
In order to leave comments, you need to log in
Solved: using ArrayDenormalizer, and setter with PHPDoc specifying data type array of Products[] objects.
True, why the method with addProduct () did not work remains a question.
Deserialization:
$encoder = [new JsonEncoder()];
$extractor = new PropertyInfoExtractor([], [new ReflectionExtractor()]);
$normalizer = [new ArrayDenormalizer(), new ObjectNormalizer(null, null, null, $extractor)];
$serializer = new Serializer($normalizer, $encoder);
/** @var $lead Lead */
$lead = $serializer->deserialize($data,Lead::class,'json');
/**
* @param Product[] $products
*/
public function setProducts(array $products)
{
$this->products = $products;
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question