doctrine/DoctrineMongoDBBundle

JSON serialization issue

Closed this issue · 1 comments

I have Businesses stored in my DB, each DB can have multiple categories attached with a simple ReferenceMany. I try to get all businesses stored in my DB simply with a findAll and serialize the list to send it in my response as JSON.
The issue is that instead of getting an category arry, I get an object which is not JSONSerializable.

Here is my Business class:

<?php
/**
 * Copyright (c) 2019 - Fidzee France
 */

namespace FidzeeCoreBundle\Document;

use Algolia\AlgoliaSearchBundle\Mapping\Annotation\Attribute;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use FidzeeCoreBundle\Document\BusinessCategory;
use Symfony\Component\HttpFoundation\File\File;
use Symfony\Component\Serializer\Annotation\Groups;
use Symfony\Component\Validator\Constraints as Assert;
use Vich\UploaderBundle\Mapping\Annotation as Vich;

/**
 * Class Business
 * @package FidzeeCoreBundle\Document
 *
 * @MongoDB\Document(repositoryClass="FidzeeCoreBundle\Repository\BusinessRepository")
 * @Vich\Uploadable()
 */
class Business implements \JsonSerializable
{

    /**
     * @var string
     * @MongoDB\Id
     * @Groups({"apiExposed"})
     * @Attribute()
     */
    private $id;

    /**
     * @var User
     * @MongoDB\ReferenceOne(targetDocument="FidzeeCoreBundle\Document\User")
     * @Groups({"apiExposed"})
     * @Attribute()
     * @Assert\NotBlank()
     */
    private $user;

    /**
     * @var string
     * @MongoDB\Field(type="string")
     * @Groups({"apiExposed"})
     * @Attribute()
     * @Assert\NotBlank()
     */
    private $name;

    /**
     * @var array
     * @MongoDB\ReferenceMany(targetDocument="FidzeeCoreBundle\Document\BusinessCategory")
     * @Attribute()
     */
    private $categories = array();
...
/**
     * @return array
     */
    public function getCategories(): array
    {
        return $this->categories;
    }

    /**
     * @param array $categories
     * @return Business
     */
    public function setCategories(array $categories): Business
    {
        $this->categories = $categories;
        return $this;
    }

    /**
     * @param BusinessCategory $category
     * @return Business
     */
    public function addCategory(BusinessCategory $category): Business
    {
        if (!in_array($category, $this -> categories)){
            $this -> categories[] = $category;
        }
        return $this;
    }
...

My BusinessCategory class is as simple:

<?php
/**
 * Copyright (c) 2019 - Fidzee France
 */

namespace FidzeeCoreBundle\Document;

use Algolia\AlgoliaSearchBundle\Mapping\Annotation\Attribute;
use Doctrine\ODM\MongoDB\Mapping\Annotations as MongoDB;
use Symfony\Component\Serializer\Annotation\Groups;

/**
 * Class BusinessCategory
 * @package FidzeeCoreBundle\Document
 *
 * @MongoDB\Document(repositoryClass="FidzeeCoreBundle\Repository\BusinessCategoryRepository")
 */
class BusinessCategory implements \JsonSerializable
{
    /**
     * @var string
     * @MongoDB\Id
     * @Groups({"apiExposed"})
     * @Attribute()
     */
    private $id;
...

What I get in response:

[
    {
        "id": "5d30ec04c94e3f314400260d",
        "user": {
            "id": "5d30ec04c94e3f3144002602",
            "email": "honore82@lefebvre.net",
            "roles": [
                "ROLE_USER"
            ],
            "accountNonExpired": true,
            "accountNonLocked": true,
            "credentialsNonExpired": true,
            "enabled": true,
            "firstname": "Arthur",
            "lastname": "Duhamel",
            "birthdate": {
                "date": "1971-06-26 06:20:38.000000",
                "timezone_type": 3,
                "timezone": "UTC"
            },
            "woman": true,
            "qrCode": "5352d207bb70a1e509730a6a5dcda4cb",
            "lastQrGen": null,
            "phone": "+33 7 54 73 69 97",
            "pictureName": "default.png",
            "updatedAt": {
                "date": "2019-07-18 22:00:46.351659",
                "timezone_type": 3,
                "timezone": "UTC"
            },
            "apiKey": "api_7ab5c21f344974adc608b55f",
            "deviceId": null,
            "awaitingVerificiation": false
        },
        "name": "Faivre",
        "categories": {}, //the issue is here
        "address": "40, place Lecomte",
        "zip": "18 946",
        "city": "Francoisnec",
        "state": "neque",
        "country": "Suède",
        "phone": "+33 6 23 27 87 08",
        "coordinates": {
            "lat": -42.867922,
            "long": 86.572524
        },
        "logo": null,
        "frontage": null,
        "settings": {
            "passMode": 0,
            "coefByAmount": 0.1,
            "pointsByPass": 1
        },
        "updatedAt": null,
        "comingSoon": false,
        "enabled": false
    },
...]

Just ask me if you want more details.

In jsonSerialize method in the Business you need to have 'categories' => $this->categories->toArray() to convert Collection instance to a plain array. Also for support questions please consider asking them on StackOverflow or our Slack channel.