5

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?

3
  • How do you output your JSON? Do you use twig or simple echo? Commented Feb 22, 2016 at 9:14
  • its a angular app which consumes the json response Commented Feb 22, 2016 at 9:16
  • @Ahmad Sajid did you checked my answer? It works for me perfectly. Commented Feb 22, 2016 at 17:10

3 Answers 3

9

I had the same problem and it not come from Serializer but the way I return the response:

Do this (Take note of the true):

return new JsonResponse($serialized, 200, array(), true);

Instead of:

return new JsonResponse($serialized);

in order to avoid JsonResponse to encode an encoded JSON and thus quoted the JSON.

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

Comments

8

I've been struggling with this problem as well. Yey I've used another approach maybe it would be good for you to know.

Symfony 2 serializer allow you to specify some options that will be used by the JsonEncoder directly passed to json_encode function. Then you can personalize your usage adding more options under the key json_encode_options of the third parameter array passed to the serialize method

$serializer->serialize($entity, 'json',  ['json_encode_options' => JSON_UNESCAPED_SLASHES]);

1 Comment

Perfect! I'm using Symfony 4.3 and this works a charm, thanks man.
2

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

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.