php - 使用 JMS Serializer 反序列化混合类型的值

标签 php symfony jms-serializer

我在使用 JMS 序列化程序时遇到了一些问题 - 我需要反序列化一个带有 score 值混合类型的脏 JSON。例如:

{ label: "hello", score: 50 }

或者

{ label: "hello", score: true }

如果我输入 @Type("int"),当值为 boolean 时,它会被反序列化为 10...
我想在值为 true 时得到 100,在值为 false 时得到 0
我如何在反序列化时管理这种混合类型?

我的类(class):

class Lorem 
{
    /**
     * @Type("string")
     * @SerializedName("label")
     * @var string
     */
    protected $label;

    /**
     * @Type("int")
     * @SerializedName("score")
     * @var int
     */
    protected $score;
}

最佳答案

你可以写下你的custom handler定义一个新的 my_custom_type(或更好地命名 :),然后您可以在注释中使用它。

像这样的东西应该可以工作:

class MyCustomTypeHandler implements SubscribingHandlerInterface 
{
    /**
     * {@inheritdoc}
     */
    public static function getSubscribingMethods()
    {
        return [
            [
                'direction' => GraphNavigator::DIRECTION_DESERIALIZATION,
                'format' => 'json',
                'type' => 'my_custom_type',
                'method' => 'deserializeFromJSON',
            ],
        ];
    }

    /**
     * The de-serialization function, which will return always an integer.
     *
     * @param JsonDeserializationVisitor $visitor
     * @param int|bool $data
     * @param array $type
     * @return int
     */
    public function deserializeFromJSON(JsonDeserializationVisitor $visitor, $data, array $type)
    {
        if ($data === true) {
            return 100;
        }
        if ($data === false) {
            return 0;
        }
        return $data;
    }
}

关于php - 使用 JMS Serializer 反序列化混合类型的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49721595/

相关文章:

php - 如何更改 Mantis 中的配置文件?

symfony - 是否可以动态更改实体属性(property)学说类型?

php - 使用 JMSSerializer 序列化特征

php - Symfony 和 JMSSerialier,无法添加监听器来添加额外字段

php - 如何使用 JMS Serializer 序列化 ArrayCollection 的切片?

php - Paypal 中的标准工作流程与 PHP codeigniter 集成

php - 这条sql语句的含义

php - 在这种简单的情况下,PHP 拒绝接受返回类型的原因是什么?

php - Symfony2/Doctrine 中的实体和模型有什么区别

php - ESI 是阻塞的还是非阻塞的?