反序列化与 Symfony Serializer Component 有关系的实体 [英] Deserialize an entity with a relationship with Symfony Serializer Component
问题描述
我正在尝试使用 symfony 序列化器组件反序列化具有关系的实体.这是我的实体:
I'm trying to deserialize an entity with a relationship using the symfony serializer component. This is my entity:
namespace AppBundleEntity;
use DoctrineORMMapping as ORM;
/**
* Document
*
* @ORMTable(name="document")
* @ORMEntity(repositoryClass="AppBundleRepositoryDocumentRepository")
*/
class Document
{
/**
* @var int
*
* @ORMColumn(name="id", type="integer")
* @ORMId
* @ORMGeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @ORMManyToOne(targetEntity="Genre", inversedBy="documents")
* @ORMJoinColumn(name="id_genre", referencedColumnName="id")
*/
private $genre;
/**
* @var string
*
* @ORMColumn(name="name", type="string", length=100)
*/
private $name;
//getters and setters down here
...
}
以及流派实体:
namespace AppBundleEntity;
use DoctrineORMMapping as ORM;
use DoctrineCommonCollectionsArrayCollection;
/**
* Genre
*
* @ORMTable(name="genre")
* @ORMEntity(repositoryClass="AppBundleRepositoryGenreRepository")
*/
class Genre
{
/**
* @var int
*
* @ORMColumn(name="id", type="integer")
* @ORMId
* @ORMGeneratedValue(strategy="AUTO")
*/
private $id;
/**
* @var string
*
* @ORMColumn(name="name", type="string", length=50, nullable=true)
*/
private $name;
/**
* @ORMOneToMany(targetEntity="Document", mappedBy="genre")
*/
private $documents;
public function __construct()
{
$this->documents= new ArrayCollection();
}
//getters and setters down here
....
}
在我的控制器操作中,我现在正在尝试:
In my controller action right now I'm trying this:
$encoders = array(new JsonEncoder());
$normalizers = array(new ObjectNormalizer());
$serializer = new Serializer($normalizers, $encoders);
$document = $serializer->deserialize($request->getContent(), 'AppBundleEntityDocument', 'json');
还有我的json 数据:
{"name": "My document", "genre": {"id": 1, "name": "My genre"}}
但是我遇到了下一个错误:
AppBundleEntityGenre"类型的预期参数,给出数组"(500内部服务器错误)
Expected argument of type "AppBundleEntityGenre", "array" given (500 Internal Server Error)
是否可以反序列化带有内部关系的实体的 json 请求?
Is possible to deserialize a json request with an entity with relations inside?
提前致谢.
推荐答案
是和否.首先,您不应在控制器中重新创建序列化程序的新实例,而应改用 serializer
服务.
Yes and no. First, you shouldn't re-create a new instance of the serializer in your controller but use the serializer
service instead.
第二,不,Symfony 序列化程序不可能开箱即用.我们在 https://api-platform.com/ 中这样做,但那里有一些魔法.也就是说,已经制作了一个 PR 来支持它:https://github.com/symfony/symfony/pull/19277
Second, no it's not possible out of the box with Symfony serializer. We are doing it in https://api-platform.com/ but there is a bit of magic there. That said, a PR has been made to support it: https://github.com/symfony/symfony/pull/19277
这篇关于反序列化与 Symfony Serializer Component 有关系的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!