gpt4 book ai didi

symfony - 使用 Symfony Serializer 时如何解决 DateTimeNormalizer 问题

转载 作者:行者123 更新时间:2023-12-01 21:57:23 26 4
gpt4 key购买 nike

我在使用 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);
}

我将包含 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}

最佳答案

tl;dr 订单很重要。

尝试:

$normalizers = [new DateTimeNormalizer(), new ObjectNormalizer()];

代替:

$normalizers = [new ObjectNormalizer(), new DateTimeNormalizer()];

关于symfony - 使用 Symfony Serializer 时如何解决 DateTimeNormalizer 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55827934/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com