这是我的情况:
我正在尝试编写一个适用于"严格"类型(整数,布尔值和浮点数)的Symfony REST API,因为默认的Symfony行为不支持它,我想避免强制强制转换类型(例如:JMS序列化程序将字符串值转换为整数字段类型)
为此,我创建了一个自定义处理程序来实现JMSSerializerHandlerSubscribingHandlerInterface
(例如StrictIntegerHandler
):
<?php
namespace AppBundleSerializer;
use JMSSerializerContext;
use JMSSerializerGraphNavigator;
use JMSSerializerHandlerSubscribingHandlerInterface;
use JMSSerializerJsonDeserializationVisitor;
use JMSSerializerJsonSerializationVisitor;
use SymfonyComponentHttpKernelExceptionBadRequestHttpException;
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 AppBundleEntity;
use DoctrineORMMapping as ORM;
use JMSSerializerAnnotation as Serializer;
use SymfonyComponentValidatorConstraints as Validator;
/**
* Person
*
* @ORMTable(name="persons")
* @ORMEntity(repositoryClass="AppBundleRepositoryPersonRepository")
*/
class Person
{
/**
* @var int age
*
* @ORMColumn(name="age", type="integer")
*
* @SerializerType("strict_integer")
* @SerializerGroups({"Person"})
*
* @ValidatorType(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映射 或者这可能是教义的多对多关系? (JMS\Serializer\Exception\LogicException)
调试堆栈跟踪向我显示从不调用serializeStrictIntegerToJSON
方法。
我该如何解决?谢谢。
我已经找到了解决方案:我必须jms/serializer
库升级到 1.5.0 版。
我的问题是我使用的是jms/serializer
(v1.1.0),其SerializationContext
类在isVisiting()
方法中抛出前一个LogicException
strict_integer
因为类型在GraphNavigator
类的方法accept()
开关大小写句子中无法识别。