M
M
Mark2020-04-26 13:23:41
symfony
Mark, 2020-04-26 13:23:41

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).


There is a JSON object, the problem is related to "products":
{
  "id": "9757241",
  "time": "1567105530",
  // другие параметры
  "products": [
    {
    "title": "Product name",
    "count": 1
    }
  ]
}


In the Lead class, which describes the object, the associated methods are:
private $products = [];

    /**
     * @return Product[]
     */
    public function getProducts()
    {
        return $this->products;
    }

    /**
     * @param Product $product
    */
    public function addProduct(Product $product): void
    {
        $this->products[] = $product;
    }


Deserialization code:
$normalizer = new ObjectNormalizer(null, null, new PropertyAccessor(), new ReflectionExtractor());
$serializer = new Serializer(array($normalizer), array(new JsonEncoder()));
$lead =  $serializer->deserialize($data, Lead::class, 'json');


I can't figure out what the problem is. In fact, when using the addProduct() method in conjunction with the PropertyAccessor class, the deserializer had to go through the array and put the objects in it into the Product class.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Mark, 2020-04-26
@MarkLb

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');

Setter for products in Lead class:
/**
     * @param Product[] $products
     */
    public function setProducts(array $products)
    {
        $this->products = $products;
    }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question