Han*_*XHX 3 php symfony jms-serializer
我在使用 JMS Serializer 时遇到了一些问题 - 我需要用混合类型的score值反序列化脏 JSON。例如:
{ label: "hello", score: 50 }
Run Code Online (Sandbox Code Playgroud)
或者
{ label: "hello", score: true }
Run Code Online (Sandbox Code Playgroud)
如果我输入@Type("int"),当值是 a 时boolean,它会被反序列化为1or 0...
我想得到100何时值是true,0何时值是false。
我如何在反序列化时管理这种混合类型?
我的课:
class Lorem
{
/**
* @Type("string")
* @SerializedName("label")
* @var string
*/
protected $label;
/**
* @Type("int")
* @SerializedName("score")
* @var int
*/
protected $score;
}
Run Code Online (Sandbox Code Playgroud)
您可以编写自定义处理程序来定义一个新的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;
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4523 次 |
| 最近记录: |