so suppose I have this
$arr = array(some object with property a,b,c,d,etc);
and you call Zend_Json::encode($arr);
instead of encoding the object within it as well, it will just return an encoded empty array: [{}]
which is an epic fail
how do I tell Zend_Json to also encode the object within the array and not just return this failure
##################### EDITalright so I actually have this method in the class:
public function toJson开发者_高级运维(){
$params = get_object_vars($this);
return Zend_Json::encode($params);
}
yet it's still only outputting an empty array
[{}]
encoding the object itself works, but not if it's inside an array
...
If you are encoding PHP objects by default the encoding mechanism can only access public properties of these objects. When a method toJson() is implemented on an object to encode, Zend_Json calls this method and expects the object to return a JSON representation of its internal state.
http://framework.zend.com/manual/en/zend.json.advanced.html#zend.json.advanced.objects2
Update : This is the piece of code I tried. And it works fine, I feel your object properties has no values.
class Hello
{
private $hello = 'Hello';
public $wolrd = ' World';
public function getProperties()
{
return get_object_vars($this);
}
}
$json = new Zend_Json();
$hello = new Hello();
echo $json->encode( array( $hello->getProperties() ) );
Result :
[{"hello":"Hello","wolrd":" World"}]
Hope fully this will work. Some thoughts from the post ;) http://blog.calevans.com/2008/02/21/zend_jsonencode-and-wth-are-all-my-properties/
By default Zend_Json::encode method uses PHP json_encode function. You need to set Zend_Json::$useBuiltinEncoderDecoder to true and implement a toJson method in your domain object which is in your array. This method should return valid json string.
class Foo
{
private $a;
private $b;
public function toJson()
{
return $json = Zend_Json::encode(array(
'a' => $this->a;
'b' => $this->b
));
}
}
Zend_Json::$useBuiltinEncoderDecoder = true;
echo Zend_Json::encode(array(new Foo()));
精彩评论