Caution: The documentation you are viewing is
for an older version of Zend Framework.
You can find the documentation of the current version at:
Advanced Usage — Zend Framework 2 2.2.10 documentation
When encoding PHP objects as JSON, all public properties of that object will be encoded in a JSON object.
JSON does not allow object references, so care should be taken not to encode objects with recursive references. If you have issues with recursion, Zend\Json\Json::encode() and Zend\Json\Encoder::encode() allow an optional second parameter to check for recursion; if an object is serialized twice, an exception will be thrown.
By default, Zend\Json\Json will decode JSON objects as associative arrays. However, if you desire an object returned, you can specify this:
// Decode JSON objects as PHP objects $phpNative = Zend\Json\Json::decode($encodedValue, Zend\Json\Json::TYPE_OBJECT);
Any objects thus decoded are returned as stdClass objects with properties corresponding to the key/value pairs in the JSON notation.
The recommendation of Zend Framework is that the individual developer should decide how to decode JSON objects. If an object of a specified type should be created, it can be created in the developer code and populated with the values decoded using Zend\Json.
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\Json calls this method and expects the object to return a JSON representation of its internal state.
Zend\Json\Json can encode PHP objects recursively but does not do so by default. This can be enabled by passing true as a second argument to Zend\Json\Json::encode().
// Encode PHP object recursively $jsonObject = Zend\Json\Json::encode($data, true);
When doing recursive encoding of objects, as JSON does not support cycles, an Zend\Json\Exception\RecursionException will be thrown. If you wish, you can silence these exceptions by passing the silenceCyclicalExceptions option:
1 2 3 4 5
$jsonObject = Zend\Json\Json::encode( $data, true, array('silenceCyclicalExceptions' => true) );
Zend\Json has two different modes depending if ext/json is enabled in your PHP installation or not. If ext/json is installed by default json_encode() and json_decode() functions are used for encoding and decoding JSON. If ext/json is not installed a Zend Framework implementation in PHP code is used for en-/decoding. This is considerably slower than using the PHP extension, but behaves exactly the same.
Still sometimes you might want to use the internal encoder/decoder even if you have ext/json installed. You can achieve this by calling:
Zend\Json\Json::$useBuiltinEncoderDecoder = true;
1 2 3 4 5 6 7 8 9 10 11