ZF-5974: Call to the method toJson when possible in Zend_Json_Encoder::_encodeObject
Description
When a class implement the method toJson, Zend_Json::encode (using the builtin encoder) should call this method when encoding object in the structure.
Here is a code sample :
<?php
set_include_path('/home/sylvain/src/ZendFramework/library');
require_once('Zend/Loader.php');
Zend_Loader::registerAutoload();
class JsonEncodable {
public function toJson() {
return '"Encodable object"';
}
}
$struct = array(
'encodable_object' => new JsonEncodable()
);
Zend_Json::$useBuiltinEncoderDecoder = true;
echo Zend_Json::encode($struct);
This code should return :
{"encodable_object":"Encodable object"}
Comments
Posted by Sylvain Filteau (sylvain) on 2009-03-09T10:24:34.000+0000
Here is my implementation of the patch
Posted by Sylvain Filteau (sylvain) on 2009-03-09T10:42:34.000+0000
Maybe it would be cleaner to add an interface (Zend_Json_Encodable) with the method toJson ?
Posted by Benjamin Eberlei (beberlei) on 2009-03-10T10:33:50.000+0000
This would only work for the internal encoder, therefore it should be implemented in such a way, that it doesnt hurt the compability with the json_encode functionality.
The use of an interface Zend_Json_Encodable is a good choice in my opinion. But we should get in touch with the ext/json author to discuss, weather and how he plans to implement nested object serialization via an interface, so that we don't drift out if a to be come php interface uses some other method instead of toJson.
Posted by Sylvain Filteau (sylvain) on 2009-03-10T12:47:20.000+0000
@Benjamin Eberlei : That's true, and I sent an email to the author of ext/json a couple of minutes ago asking him what was his plans about it
Posted by Bert Van Hauwaert (becoded) on 2009-09-11T07:34:30.000+0000
@Sylvain Filteau: Did you recieved an answer on it?
Posted by Sylvain Filteau (sylvain) on 2009-09-11T07:51:59.000+0000
@Benjamin Eberlei : I didn't receive an answer from him... and I don't think I will ever receive one ! ;)
Posted by Sylvain Filteau (sylvain) on 2010-04-01T12:28:32.000+0000
Instead of limiting my feature to the builtin encoder, maybe I could add it to the magic trick used by http://framework.zend.com/manual/1.10/…
Posted by Sylvain Filteau (sylvain) on 2010-06-03T12:10:45.000+0000
Something that could be interesting in this issue :
http://schlueters.de/blog/archives/…
Posted by Adam Lundrigan (adamlundrigan) on 2011-10-23T23:40:08.000+0000
This is a duplicate of ZF-9521.