DEV Community

Richard McHale
Richard McHale

Posted on

PHP - Creating a pretty printing JMS Serializer at runtime

I needed to create a pretty printing JMS Serializer for a unit test, and couldn't find a good example. So here's one for the next person.

Note: If doing this application wide I'd recommend using the config instead, as specified here http://jmsyst.com/bundles/JMSSerializerBundle/master/configuration#extension-reference

    private function createPrettyPrintingJsonSerializer(): Serializer
    {
        $builder = SerializerBuilder::create();
        $builder->setSerializationVisitor(
            'json',
            (new JsonSerializationVisitorFactory())->setOptions(JSON_PRETTY_PRINT)
        );
        return $builder->build();
    }
Enter fullscreen mode Exit fullscreen mode
    public function testUsingTheSerializer(): void
    {
        $serializer = $this->createPrettyPrintingJsonSerializer();

        $data = [
            'a' => 't1',
            'b' => 't2',
        ];

        print($serializer->serialize($data, 'json'));
    }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)