3

The sample codes are based on Symfony 6 and PHP 8.1.

I have written a test to verify the RESTful API endpoint /posts/{id}.

$client->jsonRequest('GET', $url);

$getByIdResponse = $client->getResponse();
echo("json response:::" . $getByIdResponse->getContent());

The JSON response output is like this.

{
  "id": "1ec8b1bc-7385-649e-b0ce-d762d4b219cb",
  "title": "test title",
  "content": "test content",
  "status": "DRAFT",
  "createdAt": "2022-02-11T09:19:56+00:00",
  "publishedAt": null,
  "tags": [],
  "comments": []
}

Note, the publishedAt in the response JSON is a null.

I tried to use the serializer component to deserialize the response content into a Post object.

$getData = $this->getContainer()->get('serializer')->deserialize($getByIdResponse->getContent(), Post::class, "json");

When running the test, I get the following exception like this.

Symfony\Component\Serializer\Exception\NotNormalizableValueException : 
Failed to denormalize attribute "publishedAt" value for class "App\Entity\Post": 
Expected argument of type "DateTime", "null" given at property path "publishedAt".

The sample codes is available on my Github account. The publishedAt of Post is a DateTime|null mixed type.

  1. What confused me is the default serialized result can not be deserialized using the same Serializer component.

  2. If possible to configure the Serializer component globally to skip null value and empty value(string, arrays and collections) like Jackson in the Java world when serializing an object into a JSON string.

Hantsy
  • 8,006
  • 7
  • 64
  • 109

0 Answers0