Francis Francis - 1 year ago 137
PHP Question

Symfony 3 app customizing JSON output

In my Symfony 3 web app I'm serializing some DB rows into Json as follows:

$doc = $this->get ( 'doctrine' );
$repo = $doc->getRepository ( 'AppBundle:Customer' );
$result = $repo->createQueryBuilder ( 'c' )->setMaxResults(25)->getQuery ()->getResult ();

$encoder = new JsonEncoder ();
$normalizer = new GetSetMethodNormalizer ();

$serializer = new Serializer ( array (
new \AppBundle\DateTimeNormalizer(), $normalizer
), array (
) );

$json = $serializer->serialize ( $result, 'json' );

This outputs the desired data, e.g:


In order to (at least initially) maintain compatibility with a legacy system, I'd like all the Json names to be in uppercase, e.g.


Is the best way to tackle this by approaching from:

  1. The Encoder

  2. The Normalizer(s)

  3. The Serializer

  4. Some other way?

Please briefly describe the suggested approach

Answer Source

You can implement your custom NameConverter a class that implements the NameConverterInterface and pass as second argument to the GetSetMethodNormalizer. As Example:

namespace AppBundle;

use Symfony\Component\Serializer\NameConverter\NameConverterInterface;

class ToUppercaseNameConverter implements NameConverterInterface

     * Converts a property name to its normalized value.
     * @param string $propertyName
     * @return string
    public function normalize($propertyName)
        return strtoupper($propertyName);

     * Converts a property name to its denormalized value.
     * @param string $propertyName
     * @return string
    public function denormalize($propertyName)


and use it as follow:

$uppercaseConverter = new ToUppercaseNameConverter();
$normalizer = new GetSetMethodNormalizer (null, $uppercaseConverter);

You can take a look at the doc Converting Property Names when Serializing and Deserializing

Hope this help

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download