How to show null value in JSON in FOS Rest Bundle with JMS Serializer?

14,455

Solution 1

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.

Solution 2

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

fos_rest:
    serializer:
        serialize_null: true

Solution 3

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

Share:
14,455
Geshan
Author by

Geshan

Geshan is a seasoned software engineer, with more than a decade of software engineering experience. Currently, in Sydney, Australia serving SimplyWallSt as a senior software engineer. He has a keen interest in REST architecture and microservices. He is actively involved with the developer community in his hometown Kathmandu, Nepal. He occasionally blogs in his free time.

Updated on June 03, 2022

Comments

  • Geshan
    Geshan almost 2 years

    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
    Geshan almost 11 years
    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.
  • Tjorriemorrie
    Tjorriemorrie almost 11 years
    Recent meaning dev-master, not stable (0.12.0)
  • Gmajoulet
    Gmajoulet over 9 years
    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.
  • lony
    lony over 8 years
    @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.