在哪里可以使用类型提示属性反序列化嵌套对象?

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

我正在尝试将数据从json转换为DTO类。我正在使用Symfony serializer。但是当我尝试反序列化时。它不解析typed property中的类型,我想symfony还不支持反序列化表单类型的属性。是这样吗?我是否必须实施我的一个

DTO:

class ElkUser
{
    public string $partnerUuid;

    public string $contractUuid;

    public DealerInfo $dealerInfo;
}

class DealerInfo
{
    public string $description;
    public int $dealerId;
    public string $dealerName;
    public bool $enabled;
    public string $registrationDate;
}

序列化器配置:

$normalizers = [
    new DateTimeNormalizer(),
    new ObjectNormalizer(
        null,
        null,
        null,
        new ReflectionExtractor
    ),

];

$serializer new Serializer($normalizers, [new JsonEncoder()]);

给我错误的测试案例:

TypeError : Typed property App\Services\CreditPilot\ElkUser::$dealerInfo must be an instance of App\Services\CreditPilot\DealerInfo, array used
$json = <<< JSON
{
  "partnerUuid": "string",
  "contractUuid": "string",
  "dealerInfo": {
    "dealerId": 0,
    "dealerName": "string",
    "enabled": true,
    "registrationDate": "2020-03-10T12:49:08.367Z",
    "contract": {
      "contractNumber": "string",
      "enabled": true,
      "creationDate": "2020-03-10T12:49:08.367Z"
    }
  }
}
JSON;

$serializer->deserialize($json, ElkUser::class, 'json');

php symfony serializer
1个回答
1
投票

will be supported natively in Symfony 5.1

[PropertyInfo组件使用几种来源(Doctrine元数据,PHP反射,PHPdoc配置等)提取有关PHP类的属性的信息。在Symfony 5.1中,我们改进了此组件以从PHP类型的属性中提取信息。

在此之前,您需要向序列化器提供some信息,以便能够推断出类型。一个PhpDoc或一个类型设置器就足够了。

© www.soinside.com 2019 - 2024. All rights reserved.