6

We are using Symfony2 FOSRestBundle with JMSSerializerBundle for developing REST APIs to be consumed by mobile developers.

The API response in JSON format returns 'null' as value of properties wherever applicable, which is generating an exception for the 3rd party library being used by mobile developers.

I don't see a solution from JMSSerializerBundle or FOSRestBundle to overwrite the value as per our requirement.

Workaround so far I can set default value in entity so that the fresh data will have some default value in database, instead of null. But this doesn't work for a one-to-one/many-to-one relationship objects, as those will return null by default instead of blank object.

Any solution to overwrite the json after serialization ?

Jeet
  • 1,587
  • 1
  • 9
  • 22

2 Answers2

6

You can use a custom visitor to do that:

<?php

namespace Project\Namespace\Serializer;

use JMS\Serializer\Context;
use JMS\Serializer\JsonSerializationVisitor;

class BlankSerializationVisitor extends JsonSerializationVisitor
{
    /**
     * {@inheritdoc}
     */
    public function visitNull($data, array $type, Context $context)
    {
        return '';
    }
}

And then, set it to your serializer with the setSerializationVisitor method or in your config file:

# app/config/config.yml
parameters:
    jms_serializer.json_serialization_visitor.class: Project\Namespace\Serializer\BlankSerializationVisitor
Seb33300
  • 7,464
  • 2
  • 40
  • 57
5

When using the FOSRestBundle, in your configuration file (generally app/config/config.yml) you can use this settings to avoid having null values:

fos_rest:
    serializer:
        serialize_null: false

If you want a custom value, you can use the serializer.post_serialize event.

PS: To have all possible options provided by the bundle, type this command:

php bin/console config:dump-reference fos_rest
COil
  • 7,201
  • 2
  • 50
  • 98
  • Setting this false will remove the null property from the response completely. But we need to show that key with blank string. – Jeet Jul 23 '15 at 08:50
  • Thanks for updating. I saw `serializer.post_serialize` giving me `ObjectEvent` which exposes full entity and I can't find out which one is object (nullable) and has been serialzed for API and need to be set as blank object/string. I think we can only add new properties to the `ObjectEvent`. – Jeet Jul 23 '15 at 09:15
  • I have the same issue. How can I replace null values by empty strings using the `serializer.post_serialize` event? No documentation is available on how to use the `ObjectEvent`. – Seb33300 Mar 31 '16 at 09:06
  • This entry is located at app/config/config.yml in case anyone doesn't know. And if you don't have that entry, you can add it right below fos_rest and of course, pass a bool to it if you want to display it or not. – Luis Milanese Jul 20 '16 at 19:50