1

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 (
            $encoder 
    ) );

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

This outputs the desired data, e.g:

 {companyname:"Microsoft"}

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.

 {COMPANYNAME:"Microsoft"}

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

1 Answer 1

1

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

<?php
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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.