Ahmad Sajid Ahmad Sajid - 1 month ago 14
JSON Question

Symfony2 serialze entity escape backslash from output

Hi I am using Symfony2 for my application. I am using the serializer component.

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

$callback = function ($dateTime) {
return $dateTime instanceof \DateTime
? $dateTime->format(\DateTime::ISO8601)
: '';
};

$normalizer->setCallbacks(array('matchAStartTime' => $callback, 'matchBStartTime'=> $callback, 'matchDate'=> $callback));
$normalizer->setIgnoredAttributes(array('createdAt', 'updatedAt'));
$serializer = new Serializer(array($normalizer), array($encoder));
$json = $serializer->serialize($entity, 'json');


but in the output i am having response like this:

\"id\":1,\"matchAStatus\":\"Live\"


my question is how can I remove that slash in output? I know in raw php there is option for escape backslash but what can I use in Symfony?

Answer

You can use JSON_UNESCAPED_SLASHES constant (php >= 5.4.0).

use Symfony\Component\Serializer\Encoder\JsonDecode;
use Symfony\Component\Serializer\Encoder\JsonEncode;

$encoder = new JsonEncoder(new JsonEncode(JSON_UNESCAPED_SLASHES), new JsonDecode(false))
Comments