JMSSerializerBundle icon indicating copy to clipboard operation
JMSSerializerBundle copied to clipboard

Force serialize nullable properties using a handler

Open ozahorulia opened this issue 10 months ago • 0 comments

Q A
Bug report? no
Feature request? yes
BC Break report? no
RFC? no

I've got a nullable property, and I want to serialize it to a specific value even if it's null. It probably can be done by triggering a handler with the specified type even if the value is null

App\Entity\Item:
    exclusion_policy: ALL
        category:
            type: App\Entity\Category

App\Entity\Category:
    exclusion_policy: ALL
        name: ~
        slug: ~
class CategoryHandler implements SubscribingHandlerInterface
{
    public static function getSubscribingMethods(): array
    {
        return [
            [
                'direction' => GraphNavigatorInterface::DIRECTION_SERIALIZATION,
                'format' => 'json',
                'type' => Category::class,
                'method' => 'toJson',
            ],
        ];
    }

    public function toJson(JsonSerializationVisitor $visitor, ?Category $category, array $type, Context $context): string
    {
        if ($category === null) {
            return ['name' => 'UNKNOWN', 'slug' => null];
        } else {
            // IF IT'S NOT NULL, USE DEFAULT SERIALIZATION FLOW
        }
    }
}
$context = SerializationContext::create();
$context->setSerializeNull(true);

return $this->serializer->serialize(new Item(category: null), 'json', $context);

Right now, output is always:

{
    "category": null,
}

And I want it to be:

{
    "category": {
        "name": "Name",
        "slug": "slug"
    }
}

ozahorulia avatar Oct 14 '23 12:10 ozahorulia