Serialization Symfony 4-无法从序列化数据创建DateTime实例
我想在Symfony 4.3的实体中持久化一些Json数据。 例如,我通常会这样做:Serialization Symfony 4-无法从序列化数据创建DateTime实例,serialization,doctrine-orm,symfony4,Serialization,Doctrine Orm,Symfony4,我想在Symfony 4.3的实体中持久化一些Json数据。 例如,我通常会这样做: public function storeMetadata(EncoderInterface $encoders, ObjectNormalizer $normalizers, EntityManagerInterface $entityManager): Response { $data = [ 'url' => 'www.google.com', 'title' =>
public function storeMetadata(EncoderInterface $encoders, ObjectNormalizer $normalizers, EntityManagerInterface $entityManager): Response
{
$data = [
'url' => 'www.google.com',
'title' => 'Nice title',
'created' => '2019-12-15 11:40:00'
];
$data = json_encode($data);
$serializer = new Serializer([$normalizers], [$encoders]);
$documentMetadata = $serializer->deserialize($data, DocumentMetadata::class, 'json');
$entityManager->persist($documentMetadata);
$entityManager->flush();
}
但是,因为我有一个datetime字段,所以出现了一个错误“无法从序列化数据创建datetime实例,因为其构造函数要求参数“time”存在。”
我知道我的日期是一个字符串,它应该是一个datetime对象,但是我如何序列化这个日期呢?谢谢
我的实体
/**
* @ORM\Column(type="datetime", nullable=true)
*/
private $created;
public function getCreated(): ?\DateTimeInterface
{
return $this->created;
}
public function setCreated(?\DateTimeInterface $created): self
{
$this->created = $created;
return $this;
}
你修好了吗?我也有类似的问题。是的,DateTimeNormalizer。$normalizer=newObjectNormalizer(null,null,null,newReflectionExtractor())$serializer=新的序列化程序([new DateTimeNormalizer(),$normalizer]);