Symfony从输出序列化实体转义反斜杠

问题描述:

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?

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))

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]);

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

return new JsonResponse($serialized);

instead of:

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

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

Hope this help. PS: sorry for my french english :).