In Symfony, I try to deserialize a set of objects of type "Activity" from a JSON file. Every object activity contains three properties:
- Intger Id.
- Property of Class type "Person" called "host".
- Array of Objects of class type "Person" called "participants".
I tried a Symfony made deserializer to deserialize objects of type Person and it worked well. But when I try to use it to deserialize an object of type Activity it gave me an error.
$serializer = new Serializer(
[new GetSetMethodNormalizer(), new ArrayDenormalizer()],
[new JsonEncoder()]
);
$members = $serializer->deserialize($json, 'ActivitiesBundle\Entity\Person[]', 'json');
The other one that failed to extract data:
$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;
}
}
The error I get is:
Type error: Argument 1 passed to ActivitiesBundle\Entity\Activity::setHost() must be an instance of ActivitiesBundle\Entity\Person
This is an extract of the JSON that contains data about activities:
[
{
"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": {
.....