Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Object handler callback returns array, but serialized object = null #594

Closed
tetele opened this issue May 25, 2016 · 2 comments
Closed

Object handler callback returns array, but serialized object = null #594

tetele opened this issue May 25, 2016 · 2 comments

Comments

@tetele
Copy link

tetele commented May 25, 2016

I have a class that needs to be serialized to an array. If I provide a serialization handler that returns an array, the returned serialized object is null

Example code:

use JMS\Serializer\Annotation\HandlerCallback;

class Container {
    private $things = array();

    public function addThing($thing) {
        $this->things[] = $thing;

        return $this;
    }

    public function getThings() {
        return $this->things;
    }

    /**
     * @HandlerCallback("json", direction = "serialization")
     */
    public function serializeToJson() {
        return $this->things;
    }
}

If I try to

$container = new Container();
$container->addThing('something'); // optional
print_r($serializer->serialize($container, 'json'));

I get a null result. It doesn't matter if the array is empty or not, if it is associative or not.

@orasik
Copy link

orasik commented Mar 8, 2017

I have exactly the same issue, did you manage to find any solution?

@goetas
Copy link
Collaborator

goetas commented Mar 9, 2017

As described in the documentation (http://jmsyst.com/libs/serializer/master/reference/annotations#handlercallback), @HandlerCallback receives an instance of the visitor, so you have to do something as

    /**
     * @HandlerCallback("xml", direction = "serialization")
     */
    public function serializeToXml(XmlSerializationVisitor $visitor)
    {
        $visitor->visitArray($this->things);
    }

@goetas goetas closed this as completed Mar 9, 2017
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants