Serializer seems to ignore default context - is this framework misuse or a bug? #46117
-
Problem:I have been learning Symfony 6 and I got stuck on a weird behaviour of the Serializer component. Default instance of Serializer service seems to be ignoring default context set in config file. I am not sure if this is a bug in the framework or rather my misunderstanding how the component and the framework work, but the situation can be easily reproduced in a fresh project. Steps to reproduce:Environment: PHP 8.1.4, Symfony CLI 5.4.7, Symfony 6.0.7.
framework:
# ...
serializer:
default_context:
json_encode_options: 128 # value of JSON_PRETTY_PRINT
public function __construct(
private \Symfony\Component\Serializer\SerializerInterface $serializer,
) {
parent::__construct();
}
protected function execute(InputInterface $input, OutputInterface $output): int
{
$io = new SymfonyStyle($input, $output);
$data = [
'foo' => 'bar',
'baz' => ['a' => 'b'],
];
$context = [
// exactly what was configured in default context
'json_encode_options' => JSON_PRETTY_PRINT,
];
$io->info($this->serializer->serialize($data, 'json')); // this should use default context
$io->info($this->serializer->serialize($data, 'json', $context)); // this uses manually configured context
return Command::SUCCESS;
}
$ bin/console -vvv app:wat
[INFO] {"foo":"bar","baz":{"a":"b"}}
[INFO] {
"foo": "bar",
"baz": {
"a": "b"
}
} If my understanding of Symfony's documentation is correct, both calls to |
Beta Was this translation helpful? Give feedback.
Replies: 5 comments 2 replies
-
It looks like the default context only gets used in the normalizer (source), so the documentation should probable be updated to specify this until support is added for every step in the serialization process |
Beta Was this translation helpful? Give feedback.
-
I just walked into exactly the same problem trying to use skip_null_values configured via the framework.yaml. The Serializer doesn't seem to pick up the default context at all. |
Beta Was this translation helpful? Give feedback.
-
Same issue here, I just try to set: serializer:
default_context:
json_encode_options: 1024 # value of JSON_PRESERVE_ZERO_FRACTION I see that run |
Beta Was this translation helpful? Give feedback.
-
my workaround is a compiler pass to change the json encoder: #47183 |
Beta Was this translation helpful? Give feedback.
-
In case someone finds this thread later: this was indeed a bug. The bug was fixed in this pull request: #47637 The fix was released in these Symfony versions:
|
Beta Was this translation helpful? Give feedback.
my workaround is a compiler pass to change the json encoder: #47183
there is also bug report #47012