diff --git a/src/Encoder.php b/src/Encoder.php index 190edc635..1bdeefe77 100644 --- a/src/Encoder.php +++ b/src/Encoder.php @@ -11,6 +11,7 @@ use Iterator; use IteratorAggregate; +use JsonSerializable; use ReflectionClass; use Zend\Json\Exception\InvalidArgumentException; use Zend\Json\Exception\RecursionException; @@ -66,6 +67,10 @@ public static function encode($value, $cycleCheck = false, $options = array()) { $encoder = new static(($cycleCheck) ? true : false, $options); + if ($value instanceof JsonSerializable) { + $value = $value->jsonSerialize(); + } + return $encoder->_encodeValue($value); } diff --git a/test/JsonTest.php b/test/JsonTest.php index ed0aecbb0..ff8c1e0a0 100644 --- a/test/JsonTest.php +++ b/test/JsonTest.php @@ -463,7 +463,29 @@ public function testToJSONSerialization() $this->assertEquals('{"firstName":"John","lastName":"Doe","email":"john@doe.com"}', $result); } - /** + public function testJsonSerializableWithBuiltinImplementation() + { + if (version_compare(PHP_VERSION, '5.4.0', 'lt')) { + $this->markTestSkipped('JsonSerializable does not exist in PHP <5.4.0.'); + } + + $encoded = Json\Encoder::encode( + new TestAsset\JsonSerializableBuiltinImpl() + ); + + $this->assertEquals('["jsonSerialize"]', $encoded); + } + + public function testJsonSerializableWithZFImplementation() + { + $encoded = Json\Encoder::encode( + new TestAsset\JsonSerializableZFImpl() + ); + + $this->assertEquals('["jsonSerialize"]', $encoded); + } + + /** * test encoding array with Zend_JSON_Expr * * @group ZF-4946 diff --git a/test/TestAsset/JsonSerializableBuiltinImpl.php b/test/TestAsset/JsonSerializableBuiltinImpl.php new file mode 100644 index 000000000..c31ff9121 --- /dev/null +++ b/test/TestAsset/JsonSerializableBuiltinImpl.php @@ -0,0 +1,26 @@ +