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.
What confused me is the default serialized result can not be deserialized using the same
Serializer
component.If possible to configure the
Serializer
component globally to skipnull
value and empty value(string, arrays and collections) like Jackson in the Java world when serializing an object into a JSON string.