如何在 Symfony Serializer 中反序列化一组对象?

编程入门 行业动态 更新时间:2024-10-17 00:24:32
本文介绍了如何在 Symfony Serializer 中反序列化一组对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

是否可以在 Symfony Serializer 中反序列化属性中的对象数组?我有一个带有 $Npc = [] 属性的 Boss 类,它需要保存一个 Npc 对象数组.我确实在文档中看到了一些示例,但它们没有说明此功能.我有一个带有 NPC 数组的 json 字符串,例如:

Is is possible in Symfony Serializer to deserialize an array of objects in a property? I have a Boss class with the $Npc = [] property that needs to hold a array of Npc objects. I did see some examples in the documentation, but they do not state this feature. I have a json string with an array of NPC's For example:

class Boss { private $Npc = []; /** * @return Npc[] */ public function getNpcs(): array { return $this->npcs; } }

我使用的是 php7.1 和 symfony/serializer 版本 ^3.3.

I am using php7.1 and symfony/serializer version ^3.3.

我已经尝试过 PhpDocExtractor,但它不会让我安装它.:(

I already tried PhpDocExtractor, but it would not let me install it. :(

这是一个可能的 JSON 值:

This is a possible JSON value:

{ "bossname": "Epic boss!", "npcs": [{ "id": 24723, "name": "Selin Fireheart", "urlSlug": "selin-fireheart", "creatureDisplayId": 22642 }] }

推荐答案

我找到了一种方法:).我通过 Composer 安装了 Symfony PropertyAccess 包.使用此包,您可以添加加法器、移除器和哈希器.这样 Symfony Serializer 会自动用正确的对象填充数组.示例:

I found a way to do this :). I installed the Symfony PropertyAccess package through Composer. With this package, you can add adders, removers and hassers. This way Symfony Serializer will automaticly fill the array with the correct objects. Example:

private $npcs = []; public function addNpc(Npc $npc): void { $this->npcs[] = $npc; } public function hasNpcs(): bool { return count($this->npcs) > 0 }

通过这种方式,您可以将 ObjectNormalizer 用于:

This way you can use the ObjectNormalizer with:

$normalizer = new ObjectNormalizer(null, null, null, new ReflectionExtractor());

编辑:至少从 v3.4 开始,您还必须创建一个卸妆方法.否则它将无法工作(没有错误或警告).

Edit: At least since v3.4 you have to create a remover method as well. Otherwise it just won't work (no error or warning).

更多推荐

如何在 Symfony Serializer 中反序列化一组对象?

本文发布于:2023-05-23 15:04:21,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1326412.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:对象   序列化   如何在   Serializer   Symfony

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!