symfony

Symfony Serializer normalize twice Date


Something is weird when I use the symfony 6.4 serializer 6.4.11. My date serialized are surrounded with double quote... I suspect the value encoded twice but why ?

this is the code:

$tmp = $value->format("Y-m-d H:i:s");
$value = $this->getSerializer()
    ->serialize($value, 'json', [DateTimeNormalizer::FORMAT_KEY => "Y-m-d H:i:s"]);

enter image description here

Same issue without specifying the date output format FYI...


Solution

  • In your first line of code, you are formatting the date correctly:

    $tmp = $value->format("Y-m-d H:i:s");
    

    But in your second line of code, you are passing the original DateTime object (stored in the $value variable) to the serializer:

    $value = $this->getSerializer()
    ->serialize($value, 'json', [DateTimeNormalizer::FORMAT_KEY => "Y-m-d H:i:s"]);
    

    This will do below things:

    1. The serializer formats the DateTime object to the string format Y-m-d H:i:s
    2. After that, above formatted string date will be encoded in JSON. Because of that it will be wrapped in double quotes.

    If you just want to format the date then you can simple do this like below:

    $date->format("Y-m-d H:i:s");
    

    I don't understand why you're using the serialize method for such a simple operation.

    But if you still want to use the serialize method, you can try using an associative array for serialization, like this:

    $data = [
        'date' => $value->format("Y-m-d H:i:s"),
        // Other fields...
    ];
    
    $jsonValue = $this->getSerializer()->serialize($data, 'json');