How to use JMSSerializer with symfony 4.2

2019-08-28 16:08发布

问题:

i am building an Api with symfony 4.2 and want to use jms-serializer to serialize my data in Json format, after installing it with

composer require jms/serializer-bundle

and when i try to use it this way :

``` demands = $demandRepo->findAll();
    return $this->container->get('serializer')->serialize($demands,'json');```

it gives me this errur :

Service "serializer" not found, the container inside "App\Controller\DemandController" is a smaller service locator that only knows about the "doctrine", "http_kernel", "parameter_bag", "request_stack", "router" and "session" services. Try using dependency injection instead.

回答1:

As I said in my comment, you could use the default serializer of Symfony and use it injecting it by the constructor.

//...

use Symfony\Component\Serializer\SerializerInterface;

//...

class whatever 
{
    private $serializer;

    public function __constructor(SerializerInterface $serialzer)
    {
        $this->serializer = $serializer;
    }

    public function exampleFunction()
    {
        //...
        $data = $this->serializer->serialize($demands, "json");
        //...
    }
}


回答2:

Let's say that you have an entity called Foo.php that has id, name and description

And you would like to return only id, and name when consuming a particular API such as foo/summary/ in another situation need to return description as well foo/details

here's serializer is really helpful.

use JMS\Serializer\Annotation as Serializer;

/*
* @Serializer\ExclusionPolicy("all")
*/
class Foo {
    /**
    * @Serializer\Groups({"summary", "details"})
    * @Serializer\Expose()
    */
    private $id;

    /**
    * @Serializer\Groups({"summary"})
    * @Serializer\Expose()
    */
    private $title;

    /**
    * @Serializer\Groups({"details"})
    * @Serializer\Expose()
    */
    private $description;

}

let's use serializer to get data depends on the group

class FooController {
    public function summary(Foo $foo, SerializerInterface $serialzer)
    {
        $context = SerializationContext::create()->setGroups('summary');
        $data = $serialzer->serialize($foo, json, $context);

        return new JsonResponse($data);
    }

    public function details(Foo $foo, SerializerInterface $serialzer)
    {
        $context = SerializationContext::create()->setGroups('details');
        $data = $serialzer->serialize($foo, json, $context);

        return new JsonResponse($data);
    }
}



回答3:

Finally i found the answer using the Symfony serializer it's very easy:

  • first : istall symfony serialzer using the command:

composer require symfony/serializer

  • second : using the serializerInterface:

.....//

use Symfony\Component\Serializer\SerializerInterface;
use Symfony\Component\HttpFoundation\JsonResponse;

// .....

.... //

 /**
     * @Route("/demand", name="demand")
     */
    public function index(SerializerInterface $serializer)
    {
        $demands = $this->getDoctrine()
            ->getRepository(Demand::class)
            ->findAll();

        if($demands){
            return new JsonResponse(
                $serializer->serialize($demands, 'json'),
                200,
                [],
                true
            );
        }else{
            return '["message":"ooooops"]';
        }

    }
    
    //......
    

and with it, i don't find any problems with dependencies or DateTime or other problems ;)