且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用Symfony 2序列化程序对对象中的嵌套结构进行反规范化

更新时间:2023-11-22 21:27:34

ObjectNormalizer需要更多配置.您至少需要提供PropertyTypeExtractorInterface类型的第四个参数.

The ObjectNormalizer needs more configuration. You will at least need to supply the fourth parameter of type PropertyTypeExtractorInterface.

这是一个(相当hacky)的例子:

Here's a (rather hacky) example:

<?php
use Symfony\Component\PropertyInfo\PropertyTypeExtractorInterface;
use Symfony\Component\PropertyInfo\Type;
use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ArrayDenormalizer;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

$a = new VehicleModel();
$a->id = 0;
$a->code = 1;
$a->model = 'modalA';
$a->make = new VehicleMake();
$a->make->id = 0;
$a->make->code = 1;
$a->make->name = 'makeA';

$b = new VehicleModel();
$b->id = 1;
$b->code = 2;
$b->model = 'modelB';
$b->make = new VehicleMake();
$b->make->id = 0;
$b->make->code = 1;
$b->make->name = 'makeA';

$data = [$a, $b];

$serializer = new Serializer(
    [new ObjectNormalizer(null, null, null, new class implements PropertyTypeExtractorInterface {
        /**
         * {@inheritdoc}
         */
        public function getTypes($class, $property, array $context = array())
        {
            if (!is_a($class, VehicleModel::class, true)) {
                return null;
            }

            if ('make' !== $property) {
                return null;
            }

            return [
                new Type(Type::BUILTIN_TYPE_OBJECT, true, VehicleMake::class)
            ];
        }
    }), new ArrayDenormalizer()],
    [new JsonEncoder()]
);

$json = $serializer->serialize($data, 'json');
print_r($json);

$models = $serializer->deserialize($json, VehicleModel::class . '[]', 'json');
print_r($models);


请注意,在示例json中,第一个条目具有一个数组作为make的值.我认为这是一个错字,如果是故意的,请发表评论.


Note that in your example json, the first entry has an array as value for make. I took this to be a typo, if it's deliberate, please leave a comment.

要使此更自动化,您可能需要尝试使用

To make this more automatic you might want to experiment with the PhpDocExtractor.