Index: library/Zend/Json/Encoder.php =================================================================== --- library/Zend/Json/Encoder.php (revision 24415) +++ library/Zend/Json/Encoder.php (working copy) @@ -135,22 +135,24 @@ } $props = ''; - - if ($value instanceof Iterator) { - $propCollection = $value; + if (method_exists($value, 'toJson')) { + $props =',' . preg_replace("/^\{(.*)\}$/","\\1",$value->toJson()); } else { - $propCollection = get_object_vars($value); - } + if ($value instanceof Iterator) { + $propCollection = $value; + } else { + $propCollection = get_object_vars($value); + } - foreach ($propCollection as $name => $propValue) { - if (isset($propValue)) { - $props .= ',' - . $this->_encodeString($name) - . ':' - . $this->_encodeValue($propValue); + foreach ($propCollection as $name => $propValue) { + if (isset($propValue)) { + $props .= ',' + . $this->_encodeString($name) + . ':' + . $this->_encodeValue($propValue); + } } } - $className = get_class($value); return '{"__className":' . $this->_encodeString($className) . $props . '}'; Index: tests/Zend/JsonTest.php =================================================================== --- tests/Zend/JsonTest.php (revision 24415) +++ tests/Zend/JsonTest.php (working copy) @@ -811,8 +811,19 @@ $this->assertEquals($targetHtmlOutput, Zend_Json::prettyPrint($jsonstr, array('format' => 'html'))); } + /** + * @group ZF-9521 + */ + public function testWillEncodeArrayOfObjectsEachWithToJsonMethod() + { + $array = array('one'=>new ToJsonClass()); + $expected = '{"one":{"__className":"ToJsonClass","firstName":"John","lastName":"Doe","email":"john@doe.com"}}'; + + Zend_Json::$useBuiltinEncoderDecoder = true; + $json = Zend_Json::encode($array); + $this->assertEquals($expected, $json); + } - } /**