4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Serializer\Tests\Encoder;
14 use PHPUnit\Framework\TestCase;
15 use Symfony\Component\Serializer\Encoder\JsonEncoder;
16 use Symfony\Component\Serializer\Serializer;
17 use Symfony\Component\Serializer\Normalizer\CustomNormalizer;
19 class JsonEncoderTest extends TestCase
24 protected function setUp()
26 $this->encoder = new JsonEncoder();
27 $this->serializer = new Serializer(array(new CustomNormalizer()), array('json' => new JsonEncoder()));
30 public function testEncodeScalar()
32 $obj = new \stdClass();
35 $expected = '{"foo":"foo"}';
37 $this->assertEquals($expected, $this->encoder->encode($obj, 'json'));
40 public function testComplexObject()
42 $obj = $this->getObject();
44 $expected = $this->getJsonSource();
46 $this->assertEquals($expected, $this->encoder->encode($obj, 'json'));
49 public function testOptions()
51 $context = array('json_encode_options' => JSON_NUMERIC_CHECK);
56 $expected = '{"foo":3}';
58 $this->assertEquals($expected, $this->serializer->serialize($arr, 'json', $context));
63 $expected = '{"foo":"3"}';
65 $this->assertEquals($expected, $this->serializer->serialize($arr, 'json'), 'Context should not be persistent');
68 protected function getJsonSource()
70 return '{"foo":"foo","bar":["a","b"],"baz":{"key":"val","key2":"val","A B":"bar","item":[{"title":"title1"},{"title":"title2"}],"Barry":{"FooBar":{"Baz":"Ed","@id":1}}},"qux":"1"}';
73 protected function getObject()
75 $obj = new \stdClass();
77 $obj->bar = array('a', 'b');
78 $obj->baz = array('key' => 'val', 'key2' => 'val', 'A B' => 'bar', 'item' => array(array('title' => 'title1'), array('title' => 'title2')), 'Barry' => array('FooBar' => array('Baz' => 'Ed', '@id' => 1)));