ZF-4682: Add support for a toJson() method to Zend_Json::encode()

Issue Type: Improvement Created: 2008-10-22T11:57:20.000+0000 Last Updated: 2010-08-12T01:13:41.000+0000 Status: Resolved Fix version(s): - 1.7.0 (17/Nov/08)

Reporter: Jurrien Stutterheim (norm2782) Assignee: Jurrien Stutterheim (norm2782) Tags: Related issues: Attachments:


Zend_Json::encode() should support reading a Json string when an object is passed. Proposed patch:

<pre class="highlight">
public static function encode($valueToEncode, $cycleCheck = false, $options = array())
    if (is_object($valueToEncode) && method_exists($valueToEncode, 'toJson')) {
        return $valueToEncode->toJson();
    if (function_exists('json_encode') && self::$useBuiltinEncoderDecoder !== true) {
        return json_encode($valueToEncode);

    require_once 'Zend/Json/Encoder.php';
    return Zend_Json_Encoder::encode($valueToEncode, $cycleCheck, $options);


Posted by Jurrien Stutterheim (norm2782) on 2008-10-22T12:08:15.000+0000

Resolved in revision 12081

Posted by Wil Sinclair (wil) on 2008-11-13T14:10:00.000+0000

Changing issues in preparation for the 1.7.0 release.

Posted by Chris Osborn (csosborn) on 2010-05-26T16:11:48.000+0000

This functionality would be far more useful if it applied to objects located anywhere in a graph being serialized, rather than just the Zend_Json::encode() argument itself. I was surprised to find, for example, that encode() calls my toJson() method when I serialize a single instance but not when I serialize an array of instances. It really should be defined recursively like the rest of the encoding process.

I'm guessing this would introduce a difference in the capabilities of the built-in and native encoders, but I think it would be worth it.

Posted by Gavin Williams (gwilli) on 2010-08-12T01:13:37.000+0000

I agree, this functionality is pretty useless unless it can be applied to objects within an array.

Have you found an issue?

See the Overview section for more details.


© 2006-2016 by Zend, a Rogue Wave Company. Made with by awesome contributors.

This website is built using zend-expressive and it runs on PHP 7.