Search code examples
phpsymfonyfosrestbundleserialization

How to pass options to json_encode function in Symfony Serializer component


here is the situation: I work on a rest api, based on symfony3, it uses FOSRestBundle and symfony serializer component, so methods return array and FOSRest handles encoding and response. The problem is serializer use json_encode with default settings and api return data like '\u00c9S' for some symbols. So I need to pass 'JSON_UNESCAPED_UNICODE' to json_encode() somehow. Is there any proper way to reach this goal? Example of a method:

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use FOS\RestBundle\Controller\Annotations as Rest;
use Nelmio\ApiDocBundle\Annotation\ApiDoc;
use Symfony\Component\HttpFoundation\Request;

/**
 * Class ExampleController
 * @package AppBundle\Controller
 */
class ExampleController extends Controller
{
    /**
     * @Rest\Get("/get-some-data")
     * @param Request $request
     * @return array
     */
    public function getSomeDataAction(Request $request)
    {
        $someData = [
            'prop1' => 'Value',
            'prop2' => 'Value',
            'prop3' => 'Value',
            'prop4' => 'Value',
        ];

        return $someData;
    }

So when I do request to '/get-some-data', it returns me:

{"prop1":"Value with \/","prop2":"Value with \u00c9"}

, but I need it to return:

{"prop1":"Value with /","prop2":"Value with É"} 

Solution

  • I use Symfony 3 and the "Doctrine JSON ODM Bundle" to store my data as JSON document. I had the same problem. All the data that contained unicode characters where automatically escaped which was not what I wanted.

    After some experiments I finally managed to pass JSON_UNESCAPED_UNICODE option to json_encode(). Below is my solution:

    # config/services.yml
    
        serializer.encode.json.unescaped:
            class: Symfony\Component\Serializer\Encoder\JsonEncode
            arguments:
               - !php/const JSON_UNESCAPED_UNICODE
    
        serializer.encoder.json:
            class: Symfony\Component\Serializer\Encoder\JsonEncoder
            arguments:
                - '@serializer.encode.json.unescaped'