瀏覽代碼

ZF-9521
Zend_Json
Zend_Json_Encoder fix when encoding array of objects each implementing toJson() method


git-svn-id: http://framework.zend.com/svn/framework/standard/trunk@24424 44c647ce-9c0f-0410-b52a-842ac1e357ba

adamlundrigan 14 年之前
父節點
當前提交
4413a2f6da
共有 2 個文件被更改,包括 27 次插入12 次删除
  1. 14 12
      library/Zend/Json/Encoder.php
  2. 13 0
      tests/Zend/JsonTest.php

+ 14 - 12
library/Zend/Json/Encoder.php

@@ -135,22 +135,24 @@ class Zend_Json_Encoder
         }
 
         $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->_encodeString($name)
-                        . ':'
-                        . $this->_encodeValue($propValue);
+            foreach ($propCollection as $name => $propValue) {
+                if (isset($propValue)) {
+                    $props .= ','
+                            . $this->_encodeString($name)
+                            . ':'
+                            . $this->_encodeValue($propValue);
+                }
             }
         }
-
         $className = get_class($value);
         return '{"__className":' . $this->_encodeString($className)
                 . $props . '}';

+ 13 - 0
tests/Zend/JsonTest.php

@@ -875,6 +875,19 @@ EOB;
         $this->assertNotSame($objJson, $arrJson);
     }
 
+    /**
+     * @group ZF-9521
+     */
+    public function testWillEncodeArrayOfObjectsEachWithToJsonMethod()
+    {
+        $array = array('one'=>new ToJsonClass());
+        $expected = '{"one":{"__className":"ToJsonClass","firstName":"John","lastName":"Doe","email":"john@doe.com"}}';
+
+        Zend_Json::$useBuiltinEncoderDecoder = true;
+        $json = Zend_Json::encode($array);
+        $this->assertEquals($expected, $json);
+    }
+
 }
 
 /**