FERRASSI Badr
FERRASSI Badr

Reputation: 104

Failed to denormalize attribute "publishedAt" value

I'm using the Serializer component to deserialize Posts from json response.

        $data = <<<EOF
        {
            "header": {
            "error": 0,
            "message": "ok",
            "next": 2
            },
            "results": [
            {
            "id": 17007,
            "title": "test article title 1",
            "publishedAt": "28/09/2020"
            },
            {
            "id": 17008,
            "title": "sample article 2",
            "publishedAt": "28/09/2020"
            }
            ]
        }
        EOF;
        $json = json_encode(json_decode($data)->results);
        $normalizers = array(new ObjectNormalizer(),new  GetSetMethodNormalizer(), new ArrayDenormalizer());
        $encoders = array(new JsonEncoder());
        $serializer = new Serializer($normalizers, $encoders);
        $posts = $serializer->deserialize($json, Post::class . '[]', 'json');
dd($posts); exit;

I get this exception :

Failed to denormalize attribute "publishedAt" value for class "App\Entity\Post": Expected argument of type "DateTime", "string" given at property path "publishedAt".

i created this simple project to show you my code https://github.com/ferrassi/sfDevs Would you have any idea about what im doing wrong?

Upvotes: 4

Views: 3854

Answers (1)

Urmat Zhenaliev
Urmat Zhenaliev

Reputation: 1557

I saw your github. You was in a right way, but you forgot to make two things:

  1. Pass extractor to ObjectNormalizer to let him denormalize other types than scalar. Pay attention to new ReflectionExtractor() in the code below
  2. Pass $context to DatetimeNormalizer with correct date format to let him create from your format

Here is working code:

        $normalizers = array(
            new DateTimeNormalizer([
                DateTimeNormalizer::FORMAT_KEY => "d/m/Y",
            ]),
            new ObjectNormalizer(
                null,
                null,
                null,
                new ReflectionExtractor()
            ),
            new GetSetMethodNormalizer(),
            new ArrayDenormalizer(),
        );
        $encoders = array(new JsonEncoder());

        $serializer = new Serializer($normalizers, $encoders);
        $posts = $serializer->deserialize($json, Post::class.'[]', 'json', [
            DateTimeNormalizer::FORMAT_KEY => "d/m/Y",
        ]);

P.S. But with autowiring you could just:

$posts = $serializer->deserialize($json, Post::class.'[]', 'json', [
    DateTimeNormalizer::FORMAT_KEY => "d/m/Y",
]);

$serializer is created via Symfony DI

Upvotes: 5

Related Questions