Search code examples
serializationuuidfosrestbundle

symfony4, FOSRestBundle and ramsey/uuid-doctrine - convert uuid object to string for REST API


I am using symfony4 for a while now and love it. Now I wanted to start with the FOSRestBundle and uuid from ramsey.

No problems so far, eveything works fine, when I call the API I get an JSON response with the fields.

The fields are:

  • id, type: uuid
  • username, type: string
  • email, type: string

The controller action that I trigger:

/**
 * @Rest\Get("/api/users", name="api_users_list")
 */
public function index()
{
    $users = $this->getDoctrine()->getRepository(User::class)->findAll();

    return View::create($users, 200);
}

The output I get:

{
    "email": "[email protected]",
    "id": {
        "codec": {
            "builder": {
                "converter": {}
            }
        },
        "converter": {},
        "factory": {
            "codec": {
                "builder": {
                    "converter": {}
                }
            },
            "node_provider": {
                "node_providers": [
                    {},
                    {}
                ]
            },
            "number_converter": {},
            "random_generator": {},
            "time_generator": {
                "node_provider": {
                    "node_providers": [
                        {},
                        {}
                    ]
                },
                "time_converter": {},
                "time_provider": {}
            },
            "uuid_builder": {
                "converter": {}
            }
        },
        "fields": {
            "clock_seq_hi_and_reserved": "a6",
            "clock_seq_low": "6c",
            "node": "a9a300ef5181",
            "time_hi_and_version": "4aa1",
            "time_low": "e3e6cdee",
            "time_mid": "5c93"
        }
    },
    "username": "apokalipscke"
}

As you can see the id field is an object, but I want it to only contains the string representation of the uuid, like: "e3e6cdee-5c93-4aa1-a66c-a9a300ef5181". I searched the internet and tried many thing but can't find an answer how to solve this.

The output I want:

{
    "id": "e3e6cdee-5c93-4aa1-a66c-a9a300ef5181",
    "username": "apokalipscke",
    "email": "[email protected]"
}

Solution

  • The correct solution for that would be adding a serializer handler for the uuid type. And luckily it's already implemented in this bundle: https://github.com/mhujer/jms-serializer-uuid-bundle

    Just install the bundle, and add a @Serializer\Type("uuid") annotation to the $id property.