ZF-4682: Add support for a toJson() method to Zend_Json::encode()
Description
Zend_Json::encode() should support reading a Json string when an object is passed. Proposed patch:
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);
}
Comments
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.