小编Bec*_*eck的帖子

使用 Symfony Serializer 时如何修复 DateTimeNormalizer 问题

我在使用 Symfony Serializer 将 DateTime 对象规范化为字符串时遇到问题。

我正在使用以下代码:

protected function createResponse($data, Int $statusCode){

    $serializedData = $this->serialize($data);

    return new Response($serializedData, $statusCode, array(
        'Content-Type' => 'application/json',
    ));

}

protected function serialize($data, string $format = 'json')
{
    $encoders = [new JsonEncoder()];
    $normalizers = [new ObjectNormalizer(), new DateTimeNormalizer()];

    $serializer = new Serializer($normalizers, $encoders);

    return $serializer->serialize($data, $format);
}
Run Code Online (Sandbox Code Playgroud)

我将包含 DateTimeInterface 变量的实体传递到上面定义的 createResponse 方法中,但日期没有被标准化为 RFC3339 格式。我错过了重要的一步吗?

我得到的示例输出:

"reportDate":{"timezone":{"name":"UTC","transitions":[{"ts":-9223372036854775808,"time":"-292277022657-01-27T08:29:52+0000","offset":0,"isdst":false,"abbr":"UTC"}],"location":{"country_code":"??","latitude":0,"longitude":0,"comments":""}},"offset":0,"timestamp":1551398400}
Run Code Online (Sandbox Code Playgroud)

serialization symfony

2
推荐指数
1
解决办法
470
查看次数

标签 统计

serialization ×1

symfony ×1