[英]Symfony: How to make JMS Serializer works with strict types?
這是我的情況:
我正在嘗試編寫一個可用於“嚴格”類型(整數,布爾值和浮點數)的Symfony REST API,因為默認的Symfony行為不支持該類型,並且我想避免強制轉換類型(例如: JMS Serializer轉換字符串值)轉換為整數字段類型 )
為此,我創建了一個自定義處理程序,該處理程序實現了JMS\\Serializer\\Handler\\SubscribingHandlerInterface
(例如StrictIntegerHandler
):
<?php
namespace AppBundle\Serializer;
use JMS\Serializer\Context;
use JMS\Serializer\GraphNavigator;
use JMS\Serializer\Handler\SubscribingHandlerInterface;
use JMS\Serializer\JsonDeserializationVisitor;
use JMS\Serializer\JsonSerializationVisitor;
use Symfony\Component\HttpKernel\Exception\BadRequestHttpException;
class StrictIntegerHandler implements SubscribingHandlerInterface
{
public static function getSubscribingMethods()
{
return [
[
'direction' => GraphNavigator::DIRECTION_DESERIALIZATION,
'format' => 'json',
'type' => 'strict_integer',
'method' => 'deserializeStrictIntegerFromJSON',
],
[
'direction' => GraphNavigator::DIRECTION_SERIALIZATION,
'format' => 'json',
'type' => 'strict_integer',
'method' => 'serializeStrictIntegerToJSON',
],
];
}
public function deserializeStrictIntegerFromJSON(
JsonDeserializationVisitor $visitor, $data, array $type)
{
return $data;
}
public function serializeStrictIntegerToJSON(
JsonSerializationVisitor $visitor, $data, array $type, Context $context)
{
return $visitor->visitInteger($data, $type, $context);
}
}
我的實體看起來:
<?php
namespace AppBundle\Entity;
use Doctrine\ORM\Mapping as ORM;
use JMS\Serializer\Annotation as Serializer;
use Symfony\Component\Validator\Constraints as Validator;
/**
* Person
*
* @ORM\Table(name="persons")
* @ORM\Entity(repositoryClass="AppBundle\Repository\PersonRepository")
*/
class Person
{
/**
* @var int age
*
* @ORM\Column(name="age", type="integer")
*
* @Serializer\Type("strict_integer")
* @Serializer\Groups({"Person"})
*
* @Validator\Type(type="integer", message="Age field has wrong type")
*/
private $age;
public function getAge()
{
return $this->age;
}
public function setAge(int $age)
{
$this->age = $age;
}
}
當我拋出以下POST操作時,JMS序列化器將返回正確的結果:
{ "age" : 12 }
將導致int(12)
{ "age" : "asdf" }
將導致"Age field has wrong type"
在這兩種情況下,都會調用我的方法deserializeStrictIntegerFromJSON
,因此反序列化過程可以按我的要求完美地工作。
問題與序列化過程有關:當我啟動GET操作( /person/id_person
)時,出現以下異常:
預期的對象,但為整數。 您是否使用了錯誤的@Type映射,或者這可能是Doctrine多對多關系? (JMS \\ Serializer \\ Exception \\ LogicException)
調試堆棧跟蹤向我展示了永遠不會調用方法serializeStrictIntegerToJSON
。
我該如何解決? 謝謝。
我找到了解決方案:我必須將jms/serializer
庫升級到1.5.0版。
我的問題是,我使用jms/serializer
(V1.1.0),其SerializationContext
類被扔上一LogicException
在isVisiting()
方法,因為strict_integer
類型未在開關的情況下判語從認識到accept()
的方法GraphNavigator
類。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.