使用JMS Serializer

时间:2018-04-08 18:58:51

标签: php symfony jms-serializer

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

{ label: "hello", score: 50 }

{ label: "hello", score: true }

如果我添加@Type("int"),当值为boolean时,会将其反序列化为10 ...
我希望当值为100时获得true,而当值为0时获得false
如何在反序列化时管理这种混合类型?

我的课程:

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

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

2 个答案:

答案 0 :(得分:2)

您可以编写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;
    }
}

答案 1 :(得分:0)

Type annotation将转换值,也许您可​​以定义类型数组,请参阅doc类似Type("array<string>,array< boolean>")

的内容
相关问题