如何在 Symfony Serializer 中反序列化一组对象? [英] How can I deserialize an array of objects in Symfony Serializer?

查看:45
本文介绍了如何在 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 中反序列化一组对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆