Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP

Loading…

[hotfix/ZF-9521] Zend\Json\Encoder #364

Closed
wants to merge 1 commit into from

2 participants

@adamlundrigan

Encoding array of objects implementing toJson() method

@weierophinney

Reviewed, merged, and pushed to master -- thanks!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
This page is out of date. Refresh to see the latest.
Showing with 27 additions and 10 deletions.
  1. +14 −10 library/Zend/Json/Encoder.php
  2. +13 −0 tests/Zend/Json/JsonTest.php
View
24 library/Zend/Json/Encoder.php
@@ -146,18 +146,22 @@ protected function _encodeObject(&$value)
$props = '';
- if ($value instanceof \Iterator) {
- $propCollection = $value;
+ if (method_exists($value, 'toJson')) {
+ $props =',' . preg_replace("/^\{(.*)\}$/","\\1",$value->toJson());
} else {
- $propCollection = get_object_vars($value);
- }
+ if ($value instanceof \Iterator) {
+ $propCollection = $value;
+ } else {
+ $propCollection = get_object_vars($value);
+ }
- foreach ($propCollection as $name => $propValue) {
- if (isset($propValue)) {
- $props .= ','
- . $this->_encodeValue($name)
- . ':'
- . $this->_encodeValue($propValue);
+ foreach ($propCollection as $name => $propValue) {
+ if (isset($propValue)) {
+ $props .= ','
+ . $this->_encodeValue($name)
+ . ':'
+ . $this->_encodeValue($propValue);
+ }
}
}
View
13 tests/Zend/Json/JsonTest.php
@@ -772,6 +772,19 @@ public function testDefaultTypeObject()
$this->assertInstanceOf('stdClass', Json\Decoder::decode('{"var":"value"}'));
}
+ /**
+ * @group ZF-9521
+ */
+ public function testWillEncodeArrayOfObjectsEachWithToJsonMethod()
+ {
+ $array = array('one'=>new ToJsonClass());
+ $expected = '{"one":{"__className":"ZendTest\\\\Json\\\\ToJSONClass","firstName":"John","lastName":"Doe","email":"john@doe.com"}}';
+
+ Json\Json::$useBuiltinEncoderDecoder = true;
+ $json = Json\Encoder::encode($array);
+ $this->assertEquals($expected, $json);
+ }
+
}
/**
Something went wrong with that request. Please try again.