【发布时间】:2017-11-14 00:44:23
【问题描述】:
如何正确序列化/反序列化 Symfony 3.2 Doctrine ODM 中的 MongoId 数组?
文档
namespace Acme\StoreBundle\Document;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
/**
* @MongoDB\Document(collection="Voter")
*/
class Voter
{
/**
* @MongoDB\Id
*/
protected $id;
/**
* @MongoDB\Collection
*/
protected $inlist;
/**
* Get id
*
* @return id $id
*/
public function getId()
{
return $this->id;
}
public function setId($id)
{
$this->id = $id;
return $this;
}
/**
* Set inlist
*
* @param collection $inlist
* @return $this
*/
public function setInlist($inlist)
{
$this->inlist = $inlist;
return $this;
}
/**
* Get inlist
*
* @return collection $inlist
*/
public function getInlist()
{
return $this->inlist;
}
}
控制器:
/**
* @Route("/voter/{id}")
* @Method({"GET"})
*/
public function getAction($id)
{
$product = $this->get('doctrine_mongodb')
->getRepository('AcmeStoreBundle:Voter')
->find($id);
if (!$product) {
throw $this->createNotFoundException('No product found for id ' . $id);
}
$serializer = $this->get('serializer');
$data = $serializer->serialize(
$product,
'json'
);
$response = new JsonResponse();
$response->setContent($data);
return $response;
}
序列化的 Json:
{
"id": "593e99a8de6c84f5ecec3094",
"inlist": [
{
"timestamp": 1417718686,
"pID": 3335,
"inc": 9127278,
"$id": "5480ab9e282e26070d8b456e"
},
{
"timestamp": 1417718686,
"pID": 3335,
"inc": 9127273,
"$id": "5480ab9e282e26070d8b4569"
},
{
"timestamp": 1417718686,
"pID": 3335,
"inc": 9127272,
"$id": "5480ab9e282e26070d8b4568"
},
{
"timestamp": 1417718686,
"pID": 3335,
"inc": 9127275,
"$id": "5480ab9e282e26070d8b456b"
},
{
"timestamp": 1417718686,
"pID": 3335,
"inc": 9127274,
"$id": "5480ab9e282e26070d8b456a"
},
{
"timestamp": 1411754988,
"pID": 2674,
"inc": 9127271,
"$id": "5425abec8f3723720a8b4567"
}
]
}
我希望将其序列化为(字符串)id 的数组,并将其反序列化回 MongoId 的数组:
{
"id": "593e99a8de6c84f5ecec3094",
"inlist": ['5425abec8f3723720a8b4567', '5480ab9e282e26070d8b456b' ...]
}
【问题讨论】:
-
只需将
inlist的条目转换为控制器中所需的格式或您认为合适的任何其他位置? -
我用 getInlist/setInlist transfom 做了一个解决方法——但不确定它是不是“正确”的方式
标签: mongodb symfony doctrine odm