gpt4 book ai didi

php - 在哪里构建使用类型提示属性反序列化嵌套对象的方法?

转载 作者:行者123 更新时间:2023-12-03 11:22:49 24 4
gpt4 key购买 nike

我正在尝试将数据从 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');

最佳答案

will be supported natively in Symfony 5.1 :

The PropertyInfo component extracts information about the properties of PHP classes using several sources (Doctrine metadata, PHP reflection, PHPdoc config, etc.) In Symfony 5.1, we improved this component to also extract information from PHP typed properties.



在此之前,您需要给 一些 序列化程序的信息,以便它能够推断类型。 PhpDoc 或类型化的 setter 就足够了。

关于php - 在哪里构建使用类型提示属性反序列化嵌套对象的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60618153/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com