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

标签 php symfony serialization

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

相关文章:

php - 为什么我的 MySQL 全文搜索不起作用?

php - Laravel 手动身份验证:Auth::attempt 始终为 false

php - 检查值是否已存在不起作用

php - 如何在 Twig 模板的 for 循环中使用 break 或 continue?

forms - 如何使用 A2lix 翻译形式使用学说 knp 可翻译扩展来订购已翻译的未翻译字段?

javascript - 检测 JavaScript 对象是否具有引用 DOM 元素的某些属性

php - 希望在新的 Mac 上开始使用 Apache、PHP、MySQL、Python、Django

javafx - 将项目从 TreeView 拖放到文本区域中

c# - 序列化 WPF DataTemplates 和 {Binding Expressions}(来自 PowerShell?)

rest - UML/API : How to model a RESTful API