Jmsserializerbundle: How can I force a property to serialize even if it's null?

Created on 10 May 2013  Â·  16Comments  Â·  Source: schmittjoh/JMSSerializerBundle

I want that all/some of the properties to appear in the serialization even if they are null.

Could try by using public_method and force check on getters, but seems a ugly workaround

Most helpful comment

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

$serializer->serialize($object, 'json', $context);

All 16 comments

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

$serializer->serialize($object, 'json', $context);

thanks :)

It works perfectly for json, but it triggers a namespace error for xml serialization

undeclared XML namespace prefix used in attribute name

how can I include this namespace in the resulting xml ?

xmlns:xsi="w3.org/2001/XMLSchema-instance"

Is it possible to set this in a configuration way?
We're using FOSRestBundle and it's impossible to set this using the context.

@AAtticus you can set the context in the View data class.

@lsmith77 Thanks for the tip. Are you refering to setSerializationContext($context)?

yes

Could you explain how to set this in the View data class with setSerializationContext?
Much appreciated.

@tonglil As it mentioned by @stof:

$serializer = JMS\SerializerBuilder::create();              
$serializedString = $serializer->serialize($data, 'xml', JMS\SerializationContext::create()->setSerializeNull(true));
// After this, something like: 
$yourViewClass->data = $serializedString; 

BTW, This nil namespace is very important for xml parsers, they just don't want to parse resulting XML without it :(

Looks like the above PR was merged. So can be closed, can't it?

Is this still not available to do via config?

@sloba88 I know it's possible in FOSRestBundle which uses JMSSerializer.
There is use:

....
fos_rest:
    routing_loader:
      default_format: json
    param_fetcher_listener: force
    serializer:
      serialize_null: true
...

Works now, thanks! I was setting it in config there and then serializing manually with JMS instead of using Rest response...

Sorry for necroposting, but I came here looking for how to configure null serialization in the SerializerBuilder. Turns out it is explained in the docs.

use JMS\Serializer\SerializationContext;

$serializer = JMS\Serializer\SerializerBuilder::create()
    ->setSerializationContextFactory(function () {
        return SerializationContext::create()
            ->setSerializeNull(true)
        ;
    })
    ->build()
;

Is it possible to serialize null only for specific property?

One of the json field of the API I need is nullable but required. I need to pass it even if it's null.

Unfortunately I think that you need a custom post serialize event listener registered on that type

Was this page helpful?
0 / 5 - 0 ratings