开发者

how to get an empty Json object with Zend_json?

开发者 https://www.devze.com 2023-03-01 12:10 出处:网络
From http://json.org/: an empty Json object is: {} I\'ve tried to get it with json_encod开发者_JAVA百科e (which is officially part of PHP):

From http://json.org/:

an empty Json object is:

{}

I've tried to get it with json_encod开发者_JAVA百科e (which is officially part of PHP):

json_encode((object)(array()))

that's what I need. But somehow I have to use Zend_json to get it:

Zend_Json::encode((object)(array()))

but the result is:

{"__className": "stdClass"}

Any ideas?

My PHP version 5.1.6; ZF version 1.7.2


For me this works perfectly:

echo '<pre>'; print_r(Zend_Json::encode((object)array())); echo '</pre>'; exit;
// Output: {}

Tested with ZF-Version 1.11.3

Also possible:

Zend_Json::encode(new stdClass());


Try

Zend_Json::encode(array());


Just in case anybody is still wondering, the internal encoder of the ZF adds the __className property to each object.
The internal encoder is used if the PECL extension json is not installed and thus the function json_encode not available (see http://php.net/manual/en/function.json-encode.php ).

Just use

preg_replace('/"__className":"[^"]+",/', '', $jsonString);

to get rid of all className elements


I find the solution as below:

$m = Zend_Json::encode($obj);
$res = str_replace('"__className":"stdClass"', '', $m);
$res = str_replace("'__className':'stdClass'", '', $res);
$res = str_replace("'__className': 'stdClass'", '', $res);
$res = str_replace('"__className": "stdClass"', '', $res);
return $res; 


To get around this in Zf2 I have added a disableClassNameDecoding option to Zend\Json\Encoder.

If you want to disable the __className output, you can use it like this:

return Zend\Json\Json::encode($object, false, array('disableClassNameDecoding' => true));

The patched file can be found on github. At some point I will add unit tests and create a pull request.

0

精彩评论

暂无评论...
验证码 换一张
取 消