3

I need the serializer to produce an empty object. Normally I would just do

json_encode(new stdClass()) --> '{}'

but the symfony serializer does

$this->get('serializer')->serialize(new  \stdClass(), 'json')) --> '[]'

I guess this is because the serializer first normalizes my data to an array, which is in this case empty.

Is there a way to get back json_encode default behaviour?

3 Answers 3

0

You can directly call encode method:

$this->get('serializer')->encode(new \StdClass(), 'json')
Sign up to request clarification or add additional context in comments.

2 Comments

This does the job if the response is only the standard object. (I guess it just does json_encode()?) But in reality I first fetch some objects with doctrine and then "mix" them with some default values. So my new stdClass() is just a part of the final json. And serializing the doctrine objects with json_encode() does not work.
I think the only way is to write your own or extend existing normalizer. You need to return object as is if it is an instance of stdClass.
0

Have a look at Versatile Object Mapper. It builds on top of symfony serializer and has even more features.

You can use the following context option to enable this behavior:

$json = $objectMapper->serialize(new \stdClass(), 'json', ['preserve_empty_objects' => true]);
// $json will ne '{}'

Comments

-1

As @sergey-fedotov suggested, you need a custom implementation.

Give the code below a try:


use Symfony\Component\Serializer\Normalizer\NormalizerInterface;

class StdClassNormalizer implements NormalizerInterface
{
    public function normalize($object, string $format = null, array $context = []): array|\stdClass
    {
        if ($object instanceof \stdClass && empty(get_object_vars($object))) {
            return new \stdClass();
        }
        return (array) $object;
    }

    public function supportsNormalization($data, string $format = null, array $context = []): bool
    {
        return $data instanceof \stdClass;
    }
}

Don't forget to register StdClassNormalizer as a Service.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.