JMSSerializerBundle icon indicating copy to clipboard operation
JMSSerializerBundle copied to clipboard

Serialization : Invalid argument supplied for foreach()

Open grimabe opened this issue 9 years ago • 8 comments

Hi,

I have a project with a bundle called UserBundle : This bundle is an extension of SonataUserBundle which inherites of FosUserBundle.

I'm using FosRestBundle to make API calls and I'm using JMS Serializer to write the response inside the API calls.

The serialization to Json worked well until I tried to serialize the User model.

When I tried to do it I got the following error:

Warning: Invalid argument supplied for foreach() in XXXX/vendor/jms/serializer/src/JMS/Serializer/GenericSerializationVisitor.php line 101

So I tried different things to solve this

  • I tried to add an exclusion_policy: ALL to my entity user class, sonata user class and fos user class without success
  • I tried to fix the issue in JMS class which provide the error
    public function visitArray($data, array $type, Context $context)
    {
        if (null === $this->root) {
            $this->root = array();
            $rs = &$this->root;
        } else {
            $rs = array();
        }

        foreach ($data as $k => $v) {
            $v = $this->navigator->accept($v, $this->getElementType($type), $context);

            if (null === $v && (!is_string($k) || !$context->shouldSerializeNull())) {
                continue;
            }

            $rs[$k] = $v;
        }

        return $rs;
    }

so to avoid the error I added the following code juste before the foreach statement:

        if(!is_array($data))
            return;

And it works now

So my question is : what is the good solution ? for now it's just a hack I guess so if anyone has an Idea ?

I can provide the whole log message if you want.

grimabe avatar Dec 16 '14 23:12 grimabe