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\Normalizer\CustomNormalizer;
17 use Symfony\Component\Serializer\Serializer;
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');
69 * @expectedException \Symfony\Component\Serializer\Exception\UnexpectedValueException
71 public function testEncodeNotUtf8WithoutPartialOnError()
74 'utf8' => 'Hello World!',
75 'notUtf8' => "\xb0\xd0\xb5\xd0",
78 $this->encoder->encode($arr, 'json');
81 public function testEncodeNotUtf8WithPartialOnError()
83 $context = array('json_encode_options' => JSON_PARTIAL_OUTPUT_ON_ERROR);
86 'utf8' => 'Hello World!',
87 'notUtf8' => "\xb0\xd0\xb5\xd0",
90 $result = $this->encoder->encode($arr, 'json', $context);
91 $jsonLastError = json_last_error();
93 $this->assertSame(JSON_ERROR_UTF8, $jsonLastError);
94 $this->assertEquals('{"utf8":"Hello World!","notUtf8":null}', $result);
96 $this->assertEquals('0', $this->serializer->serialize(NAN, 'json', $context));
99 public function testDecodeFalseString()
101 $result = $this->encoder->decode('false', 'json');
102 $this->assertSame(JSON_ERROR_NONE, json_last_error());
103 $this->assertFalse($result);
106 protected function getJsonSource()
108 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"}';
111 protected function getObject()
113 $obj = new \stdClass();
115 $obj->bar = array('a', 'b');
116 $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)));