gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 14:24:02 24 4
gpt4 key购买 nike

我在使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com