Search code examples
phpjmsserializerbundlesymfonyjms-serializer

How to Initialize JMS Serializer in Symfony3?


I am trying to use the JMSSerializerBundle for Symfony3 (which just came out).

These are the namespaces I've loaded in my TestController.php

use JMS\Serializer\Serializer; use JMS\Serializer\SerializerBuilder; use JMS\Serializer\SerializationContext;

I've tried $data = $this->get('jms_serializer')->serialize($data, 'json'); where $data is just a simple object, but get the following error:

Attempted to call an undefined method named "get" of class "AppBundle\Controller\TestController"

I've also tried a usage example from the site $serializer = $container->get('jms_serializer');, but get Notice: Undefined variable: container

I am still new to Symfony3 and its bundles, and can't seem to find any documention on JMS Serializer for symfony 3

I can initialize it like this $serializer = SerializerBuilder::create()->build(); which allows me to call the serialize method, but I would like to know the correct "symfony way" of doing it.

If anyone can shed some knowledge, that would be great. Thanks!


Solution

  • in order to use container in your controller, your controller must extend Symfony\Bundle\FrameworkBundle\Controller\Controller or at least use Symfony\Component\DependencyInjection\ContainerAware,

    anyway if you want to start developing in Symfony I suggest you to start reading error messages, in this specific case your errors are very clear.