0

The following error occurs during object deserialization:

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

Have JSON-object:

{
  "id": "9757241",
  "time": "1567105530",
  // other params
  "products": [
    {
    "title": "Product name",
    "count": 1
    }
  ]
}

In the Lead class that describes the object related methods to "products":

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 understand what the problem is. It is expected using the addProduct() method deserializer should bypass the array and add all objects to Product class like in this case.

1 Answer 1

0

I decided using an ArrayDenormalizer, and a setter with PHPDoc indicating the data type, an array of Products [] objects. But why the method with addProduct () did not work - the question remains.

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 the Lead class:

/**
* @param Product[] $products
*/
public function setProducts(array $products)
{
$this->products = $products;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.