schmittjoh / JMSSerializerBundle

Easily serialize, and deserialize data of any complexity (supports XML, JSON, YAML)
http://jmsyst.com/bundles/JMSSerializerBundle
MIT License
1.8k stars 312 forks source link

Force serialize nullable properties using a handler #938

Open ozahorulia opened 11 months ago

ozahorulia commented 11 months ago
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"
    }
}