schmittjoh / JMSSerializerBundle

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

configuration for allows_root_null being ignored? #921

Closed engagit closed 1 year ago

engagit commented 1 year ago

I believe I am misunderstanding something and this is unlikely a bug.

I am experiencing the error seen in this issue: https://github.com/schmittjoh/JMSSerializerBundle/issues/788

However, I read the entire thread, installed jms serializer version 3.10 and added the new configuration for "allows_root_null" and I am still getting the error.

Note that I am using Symfony v5.4

Here is my config.yml:

jms_serializer:
  default_context:
    serialization:
      serialize_null: false
      attributes:
        allows_root_null: true

In my controller, I am creating the serializer, and creating a new context so I can set the serializer groups:

use JMS\Serializer\SerializerBuilder;
use JMS\Serializer\SerializationContext;
...
$serializer = SerializerBuilder::create()->build();
$data = $serializer->serialize($myObjects, 'json', SerializationContext::create()->setGroups(array('list')));

If $myObjects is equal to NULL, then I get the error: request.CRITICAL: Uncaught PHP Exception JMS\Serializer\Exception\NotAcceptableException "" at /var/www/html/vayu/backend/vendor/jms/serializer/src/GraphNavigator/SerializationGraphNavigator.php line 144 {"exception":"[object] (JMS\\Serializer\\Exception\\NotAcceptableException(code: 0): at /var/www/html/vayu/backend/vendor/jms/serializer/src/GraphNavigator/SerializationGraphNavigator.php:144)"} []

Am I incorrect to believe that creating a new SerializationContext will use the default context settings from my config.yml?

I expected that using the above configuration meant that when I created a new Serialization Context, it would have the "default_context" settings from my config file.

goetas commented 1 year ago

SerializationContext::create() does not use the default_context configs.

if you are using symfony , you need to use the jms_serializer.serialization_context_factory to create a new context

engagit commented 1 year ago

I thought it must be something like that. Thank you very much for your help and for pointing me to the solution.