Search code examples
phpjsonsymfonyjson-deserialization

Deserialize nested JSON into entity using Symfony


How do I deserialize the photos collection in to a Photo entity using Symfony?

Here is my json:

{
    "id": 3,
    "status": 1,
    "title": "sometitle",
    "agency": {
        "id": 1,
        "name": "AgencyName",
        ...
        "created_at": "-0001-11-30T00:00:00+01:00",
        "updated_at": "-0001-11-30T00:00:00+01:00"
    },
    "price": "123123",
    ...
    "created_at": "-0001-11-30T00:00:00+01:00",
    "updated_at": "-0001-11-30T00:00:00+01:00",
    "photos": [
        {
            "id": 1,
            "path": "img1.jpg",
            "created_at": "2018-04-05T15:29:47+02:00",
            "updated_at": "2018-04-05T15:29:47+02:00"
        },
        {
            "id": 2,
            "path": "img2.jpg",
            "created_at": "2018-04-05T15:35:28+02:00",
            "updated_at": "2018-04-05T15:35:28+02:00"
        }
    ]
}

How do I specify in the Photo entity that it should use the collection as manytoone?

This is not working:

\Entity\Photo.php
/**
 * @ORM\ManyToOne(targetEntity="House", inversedBy="photos")
 */
private $house;

\Entity\House.php
/**
 * @ORM\OneToMany(targetEntity="Photo", mappedBy="house")
 */
private $photos;

When I call it in my view:

{% for photo in house.photos %}
    <li>{{ photo.path }}</li>
{% endfor %}

It is throwing an excepting and is trying to send another GET request toa different route in the API instead of just using the nested collection


Solution

  • You can use Symfony Serializer Component: https://symfony.com/doc/3.4/components/serializer.html

    example:

    $house = $serializer->deserialize($json, House::class, 'json');