2

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

##################### EDIT

alright 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

...

1
  • Are they protected or private properties? Commented Aug 17, 2011 at 9:46

2 Answers 2

2

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/

Sign up to request clarification or add additional context in comments.

1 Comment

+1, a simple implementation of toJson can just simply create a new stdClass, copy the value of non-public properties to this object and then return Zend_Json::encode(myValueObject);
0

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()));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.