在Symfony中,我尝试从JSON文件反序列化“活动”类型的一组对象。每个对象活动都包含三个属性:
我尝试使用Symfony制造的反序列化器对Person类型的对象反序列化,并且效果很好。但是,当我尝试使用它反序列化Activity类型的对象时,它给了我一个错误。
$serializer = new Serializer(
[new GetSetMethodNormalizer(), new ArrayDenormalizer()],
[new JsonEncoder()]
);
$members = $serializer->deserialize($json, 'ActivitiesBundle\Entity\Person[]', 'json');
另一个未能提取数据的人:
$activities = $serializer->deserialize($json,
'ActivitiesBundle\Entity\Activity[]', 'json');
class Activity
{
private $id;
private $host;
private $participants = [];
public function getId()
{
return $this->id;
}
public function setId($id)
{
$this->id = $id;
return $this;
}
public function getHost() {
return $this->host;
}
public function setHost(Person $host) {
$this->host = $host;
return $this;
}
public function getParticipants() {
return $this->participants;
}
public function setParticipants(\Person ... $participants) {
$this->participants = $participants;
return $this;
}
}
class Person
{
private $id;
private $name;
public function getId()
{
return $this->id;
}
public function setId($id)
{
$this->id = $id;
return $this;
}
public function getName() {
return $this->name;
}
public function setName($name) {
$this->name = $name;
return $this;
}
}
我得到的错误是:
Type error: Argument 1 passed to ActivitiesBundle\Entity\Activity::setHost() must be an instance of ActivitiesBundle\Entity\Person
这是JSON的一部分,其中包含有关活动的数据:
[
{
"id": 1,
"host": {
"id": 48,
"name": "Name48",
},
"participants": [
{
"id": 975,
"name": "Name975",
},
{
"id": 866,
"name": "Name866",
},
{
"id": 355,
"name": "Name355",
},
{
"id": 856,
"name": "Name856",
}
]
},
{
"id": 2,
"host": {
.....