[英]Deserialize value of mixed type with JMS Serializer
我在使用JMS序列化器時遇到了一些麻煩-我需要使用score
類型的混合類型反序列化臟JSON。 例如:
{ label: "hello", score: 50 }
要么
{ label: "hello", score: true }
如果我輸入@Type("int")
,則當值是boolean
,它將反序列化為1
或0
...
我想在值為true
時得到100
,在值為false
時得到0
。
如何在反序列化上管理這種混合類型?
我的課:
class Lorem
{
/**
* @Type("string")
* @SerializedName("label")
* @var string
*/
protected $label;
/**
* @Type("int")
* @SerializedName("score")
* @var int
*/
protected $score;
}
您可以編寫自定義處理程序,定義一個新的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;
}
}
Type annotation
將強制轉換值,也許您可以定義Type數組,請參見doc之類的Type("array<string>,array< boolean>")
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.