使用symfony 2序列化器对对象中的嵌套结构进行非规范化

ker*_*zen 13 php json denormalization symfony

我正在使用版本2.8的Symfony 2项目,我正在使用内置组件Serializer - > http://symfony.com/doc/current/components/serializer.html

我有一个由Web服务提供的JSON结构.反序列化后,我想在对象中反规范化我的内容.这是我的结构(汽车应用程序上下文中的模型/品牌).

[{
"0": {
    "id": 0,
    "code": 1,
    "model": "modelA",
    "make": {
        "id": 0,
        "code": 1,
        "name": "makeA"
    }
  }
} , {
 "1": {
    "id": 1,
    "code": 2,
    "model": "modelB",
    "make": {
        "id": 0,
        "code": 1,
        "name": "makeA"
    }
  }
}]
Run Code Online (Sandbox Code Playgroud)

我的想法是填充一个VehicleModel包含对象引用的VehicleMake对象.

class VehicleModel {
    public $id;
    public $code;
    public $model;
    public $make; // VehicleMake
}
Run Code Online (Sandbox Code Playgroud)

这是我做的:

// Retrieve data in JSON
$data = ...
$serializer = new Serializer([new ObjectNormalizer(), new ArrayDenormalizer()], [new JsonEncoder()]);
$models = $serializer->deserialize($data, '\Namespace\VehicleModel[]', 'json');
Run Code Online (Sandbox Code Playgroud)

结果,我的对象VehicleModel被正确填充,但$make在逻辑上是一个键/值数组.在这里,我想要一个VehicleMake代替.

有没有办法做到这一点 ?

谢谢

Yos*_*shi 7

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

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

<?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);
Run Code Online (Sandbox Code Playgroud)

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

为了使这更加自动化,您可能需要尝试使用PhpDocExtractor.