我正在使用的:
我正在使用JMSSerializerBundle从 POST 请求反序列化我的 JSON 对象
。
问题描述:
我的 JSON
中的值之一是 Id
。我想在反序列化发生之前将此 Id 替换为正确的对象。
不幸的是,JMSSerializerBundle
没有@preDeserializer
注释。
我面临的问题(如果有 @preDeserializer 注释的话我也会面临这个问题)是我想为我的所有实体创建一个通用函数。
问题:
如何以最通用的方式将我的 Id
替换为相应的对象
?
最佳答案
您也可以像我一样进行自己的补水(使用 Doctrine):
解决方案
IHydratingEntity
是我所有实体都实现的接口(interface)。
一般在我的 BaseService 中使用 Hydrate
函数。参数是实体和json对象。
在每次迭代时,该函数都会测试该方法是否存在,然后调用reflection
函数来检查参数的方法(setter)是否也实现了IHydratingEntity
。
如果是这种情况,我会使用 id
通过 Doctrine ORM 从数据库中获取实体。
我认为可以优化此流程,因此请务必分享您的想法!
protected function hydrate(IHydratingEntity $entity, array $infos)
{
#->Verification
if (!$entity) exit;
#->Processing
foreach ($infos as $clef => $donnee)
{
$methode = 'set'.ucfirst($clef);
if (method_exists($entity, $methode))
{
$donnee = $this->reflection($entity, $methode, $donnee);
$entity->$methode($donnee);
}
}
}
public function reflection(IHydratingEntity $entity, $method, $donnee)
{
#->Variable declaration
$reflectionClass = new \ReflectionClass($entity);
#->Verification
$idData = intval($donnee);
#->Processing
foreach($reflectionClass->getMethod($method)->getParameters() as $param)
{
if ($param->getClass() != null)
{
if ($param->getClass()->implementsInterface(IEntity::class))
#->Return
return $this->getDoctrine()->getRepository($param->getClass()->name)->find($idData);
}
}
#->Return
return $donnee;
}
关于php - 通用反序列化: JSON ID value to Object,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33397017/