如何处理自定义序列化器中属性的属性?

问题描述 投票:0回答:1

我有基于symfony5.4的应用程序。在这个应用程序中,我为客户提供了一个这样的课程:

class Client
{
    #[Context([DateTimeNormalizer::FORMAT_KEY => 'Y-m-d'])]
    public \DateTimeImmutable $passportIssuedDate;

    #[Context([DateTimeNormalizer::FORMAT_KEY => \DateTimeImmutable::ATOM])]
    public \DateTimeImmutable $agreementDateTime;
}

有自定义序列化器:

$encoders = [new JsonEncoder()];
$extractor = new PropertyInfoExtractor([], [new PhpDocExtractor(), new ReflectionExtractor()]);
$normalizers = [
    new DateTimeNormalizer(),
    new ObjectNormalizer(propertyTypeExtractor: $extractor),
];
$serializer = new Serializer($normalizers, $encoders);

如果我调用标准自动连线序列化器

$this->serializer->serialize($client, 'json');

我得到这个结果

{"passportIssuedDate":"2024-04-05","agreementDateTime":"2024-04-05T11:59:32+00:00"}

但如果是定制的,我会看到这一点:

{"passportIssuedDate":"2024-04-05T11:59:32+00:00","agreementDateTime":"2024-04-05T11:59:32+00:00"}

我需要如何更改自定义序列化程序才能正确处理上下文属性?

php symfony symfony-serializer
1个回答
0
投票

当您创建

ObjectNormalizer
时,您需要传递一个
ClassMetadataFactory
AttributeLoader
创建:

require('vendor/autoload.php');

use Symfony\Component\PropertyInfo\Extractor\ReflectionExtractor;
use Symfony\Component\Serializer\Serializer;
use Symfony\Component\Serializer\Annotation\Context;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Mapping\Factory\ClassMetadataFactory;
use Symfony\Component\Serializer\Mapping\Loader\AttributeLoader;
use Symfony\Component\Serializer\Normalizer\DateTimeNormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;

class Client
{
    #[Context([DateTimeNormalizer::FORMAT_KEY => 'Y-m-d'])]
    public \DateTimeImmutable $passportIssuedDate;

    #[Context([DateTimeNormalizer::FORMAT_KEY => \DateTimeImmutable::ATOM])]
    public \DateTimeImmutable $agreementDateTime;
}

$encoders = [new JsonEncoder()];
$extractor = new ReflectionExtractor();
$classMetadataFactory = new ClassMetadataFactory(new AttributeLoader());
$normalizers = [
    new DateTimeNormalizer(),
    new ObjectNormalizer($classMetadataFactory, null, null, $extractor),
];
$serializer = new Serializer($normalizers, $encoders);

$client = new Client();
$client->passportIssuedDate = new DateTimeImmutable('2024-04-05');
$client->agreementDateTime = new DateTimeImmutable('2024-04-05');
echo $serializer->serialize($client, 'json');

输出:

{"passportIssuedDate":"2024-04-05","agreementDateTime":"2024-04-05T00:00:00+00:00"}
© www.soinside.com 2019 - 2024. All rights reserved.