6

Im trying to serialize an object and skipping null value this is the object i try to serialize:

{
  key1: null
  key2: null
  key3: {
     keyA: null
     keyB: 'value'
  }
  key4: 'value'
}

if i use the following method :

$object = self::getInstance()->serialize($object, "json", ['skip_null_values' => true]);

the object is succesfully serialized but it only remove the null key of the first level and not the one from the key3 object.

{
  key3: {
     keyA: null
     keyB: 'value'
  }
  key4: 'value'
}

Is there any way to achieve this using the Symfony Serializer Component ?

3 Answers 3

3

You can use AbstractObjectNormalizer::SKIP_NULL_VALUES flag to skip null values when normalizing:

$json = $serializer->serialize(
    $user,
    JsonEncoder::FORMAT,
    [AbstractObjectNormalizer::SKIP_NULL_VALUES => true]
);

Source: https://lindevs.com/skip-null-values-during-serialization-in-symfony/

Sign up to request clarification or add additional context in comments.

Comments

-1

You can consider JMSSerializerBundle instead of Symfony serializer

it's easy to use. You can serialize nulls as empty strings

$context = new SerializationContext();
$context->setSerializeNull(true);
$objectData = $serializer->serialize($object, 'json', $context);

Comments

-1

You can use the context to pass setSerializeNull(true)

use FOS\RestBundle\Context\Context;

in your function:

$data = ...
$view = $this->view($data, 200);

$context = new Context();
$context->setSerializeNull(true);
$view->setContext($context);

return $this->handleView($view);

1 Comment

OP use symfony/serializer, not JMS/serializer

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.