38

I had a read through this : https://github.com/schmittjoh/serializer/issues/77 but did not find any way to serialize null values in JSON for FOS Rest bundle with JMS serializer (meaning just show the key of the Doctrine object even if its null).

I am using the following config in composer.json

"jms/serializer-bundle": "0.12.*@dev",
"friendsofsymfony/rest-bundle": "0.13.*@dev",

The JMS serializer config

#jms-serializer
jms_serializer:
 visitors:
    json:
        options: 0 # json_encode options bitmask
        serialize_null: true

Or the FOS Rest bunde config

fos_rest:
view:
    serialize_null: true

Does not work. I'm not using a view I'm "view_response_listener: 'force'" so if a solution from the config can be provided it would help, thanks.

Geshan
  • 1,141
  • 2
  • 11
  • 21

3 Answers3

100

You can set the following option in the config since recently:

fos_rest:
    serializer:
        serialize_null: true
Itako
  • 2,049
  • 3
  • 16
  • 19
28

Try this

in your controller

    $entity = $this->getEntity($id);

    $context = new SerializationContext();
    $context->setSerializeNull(true);

    $serializer = $this->get('jms_serializer');

    $response = new Response($serializer->serialize($entity, 'json', $context));
    $response->headers->set('Content-Type', 'application/json');

    return $response;

But the interaction with the fosrestbundle about configs is not known to me.

stwe
  • 1,262
  • 15
  • 18
  • Where should I do this the controller is extended from symfony controller and I'm not even using view I"m just returning an object. – Geshan May 28 '13 at 13:41
  • I'm sorry to downvote because the answer does work. But a Controller isn't the proper place to write this kind of logic. This logic should be consistent over all the project and therefore be in a global config file. – Gmajoulet Dec 22 '14 at 11:06
  • @stwe Is it possible to add this as a "hook"? I have a lot of controllers already and would love to "enable" this by default. Sadly I do not use fos_rest and it seems there is no configuration option for symfony or jms itself. – lony Sep 25 '15 at 09:12
4

The easiest way to make this feature works like a charm

Add the following extra configuration to your fos_rest config option:

fos_rest:
    serializer:
        serialize_null: true
Mustapha GHLISSI
  • 1,485
  • 1
  • 15
  • 16