原始碼分析系列之json_encode()如何轉化一個物件
json_encode()如何轉化一個物件? 使用 json_encode() 將陣列 array 轉化成 json 字串我們都已經很熟悉了
那麼使用 json_encode() 轉化一個物件是什麼樣的過程呢?
初步測試
我們需要新建一個具有多種屬性的物件
新建 JsonTest
class JsonTest
{
public const TEST = 'c';
public $a = 'a';
public static $b = 'b';
protected $e = 'e';
private $d = 'd';
protected function test1()
{
return __FUNCTION__;
}
private function test2()
{
return __FUNCTION__;
}
public function test3()
{
return __FUNCTION__;
}
public static function test4()
{
return __FUNCTION__;
}
}
執行 列印結果
echo json_encode(new JsonTest());
輸gtUDmYw出
{ "a": "a" }
可以看得出,只有公開非靜態的屬性被打印出來了,其他東西(常量、私有變數、方法等等)都丟失了。
思考
在實際的應用中,多數情況下,我們的屬性都是非公開的,但是我們又想在執行 json_encode() 的時候將它打印出來,該怎麼辦呢?
JsonSerializable
JsonSerializable 是一個 php 的 JSON 序列化介面
官方定義
JSON 序列化介面
(PHP 5 >= 5.4.0,PHP 7)
簡介
實現 JsonSerializable 的類可以 在 json_encode() 時定製他們的 JSON 表示法。
介面摘要
JsonSerializable {
/* 方法 */
abstract public jsonSerialize ( void ) : mixed
}
可以看出 phphttp://www.cppcns.com 版本低於 5.4 是沒有這個介面的
修改 JsonTest 繼續測試
修改 JsonTest 讓它實現 JsonSerializable,併為其寫一個 jsonSerialize 方法
class JsonTest implements JsonSerializable
{
public const TEST = 'c';
public $a = 'a';
public static $b = 'b';
protected $e = 'e';
private $d = 'd';
protected function test1()
{
return __FUNCTION__;
}
private function test2()
{
return __FUNCTION__;
}
public function test3()
{
return __FUNCTION__;
}
public static function test4()
{
return __FUNCTION__;
}
public function jsonSerialize()
{
$json = array();
foreach ($this as $key => $value) {
$json[$key] = $value;
}
return $json;
}
}
執行 列印結果
echo json_encode(new JsonTest());
輸出
{ "a": "a","e": "e","d": "d" }
可以看得出,公開屬性和私有屬性都被打印出來了,方法,常量以及靜態變數沒有打印出來(這是因為類(class)中靜態變數和常量的實現方式是所有物件共享的,並不具體屬於某個類)
原始碼分析
這部分原始碼較多,我會按照原始碼中的 function 來一個一個進行分析,注意看程式碼塊中的註釋
裡邊對應有一些 option 的位運算,我先貼出來每個 option 常量對應的值, << 是左移
/* json_encode() options */ #define PHP_JSON_HEX_TAG (1<<0) #define PHP_JSON_HEX_AMP (1<<1) #define PHP_JSON_HEX_APOS (1<<2) #define PHP_JSON_HEX_QUOT (1<<3) #define PHP_JSON_FORCE_OBJECT (1<<4) #define PHP_JSON_NUMERIC_CHECK (1<<5) #define PHP_JSON_UNESCAPED_SLASHES (1<<6) #define PHP_JSON_PRETTY_PRINT (1<<7) #define PHP_JSON_UNESCAPED_UNICODE (1<<8) #define PHP_JSON_PARTIAL_OUTPUT_ON_ERROR (1<<9) #define PHP_JSON_PRESERVE_ZERO_FRACTION (1<<10) #define PHP_JSON_UNESCAPED_LINE_TERMINATORS (1<<11)
函式本身
PHP_JSON_API int php_json_encode(smart_str *buf,zval *val,int options) /* {{{ */
{
return php_json_encode_ex(buf,val,options,JSON_G(encode_max_depth));
}
PHP_JSON_API int php_json_encode_ex(smart_str *buf,int options,zend_long depth) /* {{{ */
{
php_json_encoder encoder;
int return_code;
// 初始化,開闢記憶體空間
php_json_encode_init(&encoder);
encoder.max_depth = depth;
// 真正用於編碼的函式體
return_code = php_json_encode_zval(buf,&encoder);
JSON_G(error_code) = encoder.error_code;
return return_code;
}
/* }}} */
可以看出真正的編碼函式是 php_json_encode_zval()
php_json_encode_zval()
smart_str_appendl() 是一個拼接字串的函式,第三個引數是字串的長度
buf 就是最終要返回的 json 字串
int php_json_encode_zval(smart_str *buf,php_json_encoder *encoder) /* {{{ */
{
again:
switch (Z_TYPE_P(val))
{
case IS_NULL:
smart_str_appendl(buf,"null",4);
break;
case IS_TRUE:
smart_str_appendl(buf,"true",4);
break;
case IS_FALSE:
smart_str_appendl(buf,"false",5);
break;
case IS_LONG:
smart_str_append_long(buf,Z_LVAL_P(val));
break;
case IS_DOUBLE:
if (php_json_is_valid_double(Z_DVAL_P(val))) {
php_json_encode_double(buf,Z_DVAL_P(val),options);
} else {
encoder->error_code = PHP_JSON_ERROR_INF_OR_NAN;
smart_str_appendc(buf,'0');
}
break;
case IS_STRING:
return php_json_escape_string(buf,Z_STRVAL_P(val),Z_STRLEN_P(val),encoder);
case IS_OBJECT:
// 如果物件實現了JsonSerializable,就將物件中的jsonSerialize()返回的結果進行編碼
if (instanceof_function(Z_OBJCE_P(val),php_json_serializable_ce)) {
return php_json_encode_serializable_object(buf,encoder);
}
// 如果物件沒有實現了JsonSerializable,就執行下邊的這個php_json_encode_array()
/* fallthrough -- Non-serializable object */
case IS_ARRAY:
// 解析陣列
return php_json_encode_array(buf,encoder);
case IS_REFERENCE:
//忽略引用
val = Z_REFVAL_P(val);
goto again;
default:
encoder->error_code = PHP_JSON_ERROR_UNSUPPORTED_TYPE;
if (options & PHP_JSON_PARTIAL_OUTPUT_ON_ERROR) {
smart_str_appendl(buf,4);
}
return FAILURE;
}
return SUCCESS;
}
/* }}} */
php_json_encode_array()
這個函式遞迴編碼陣列及沒有實現JsonSerializable()的物件(只編碼物件的公開屬性)
static int php_json_encode_array(smart_str *buf,php_json_encoder *encoder) /* {{{ */
{
int i,r,need_comma = 0;
HashTable *myht;
// r用來表示輸出 `json` 的結構型別是陣列還是物件
// 只有自然排序的陣列(['a','b','c'])才有可能被輸出為陣列(考慮option可能為JSON_FORCE_OBJECT)
if (Z_TYPE_P(val) == IS_ARRAY) {
// 如果是陣列
myht = Z_ARRVAL_P(val);
// options中有JSON_FORCE_OBJECT 就強制輸出物件,否則就判斷陣列是不是自然陣列
r = (options & PHP_JSON_FORCE_OBJECT) ? PHP_JSON_OUTPUT_OBJECT : php_json_determine_array_type(val);
} else {
myht = Z_OBJPROP_P(val);
//物件就是輸出物件
r = PHP_JSON_OUTPUT_OBJECT;
}
if (myht && ZEND_HASH_GET_APPLY_COUNT(myht) > 0) {
encoder->error_code = PHP_JSON_ERROR_RECURSION;
smart_str_appendl(buf,4);
return FAILURE;
}
PHP_JSON_HASH_APPLY_PROTECTION_INC(myht);
if (r == PHP_JSON_OUTPUT_ARRAY) {
//輸出為陣列 就用 [ 做開頭
smart_str_appendc(buf,'[');
} else {
//輸出為物件 就用 { 做開頭
smart_str_appendc(buf,'{');
}
// 當前遞迴的深度
++encoder->depth;
// zend_hash_num_elements 返回雜湊表中元素的數量
i = myht ? zend_hash_num_elements(myht) : 0;
if (i > 0) {
zend_string *key;
zval *data;
zend_ulong index;
//遍歷當前維度的陣列 如果當前元素不是陣列
ZEND_HASH_FOREACH_KEY_VAL_IND(myht,index,key,data) {
// ↓ begin 從這裡開始都是判斷key怎麼處理以及元素末尾怎麼處理 ↓↓↓↓
if (r == PHP_JSON_OUTPUT_ARRAY) {
//need_comma初始值是0
if (need_comma) {
www.cppcns.comsmart_str_appendc(buf,',');
} else {
need_comma = 1;
}
//這兩個方法是option中有JSON_PRETTY_PRINT的時候才會執行的
php_json_pretty_print_char(buf,'\n');
php_json_pretty_print_indent(buf,encoder);
} else if (r == PHP_JSON_OUTPUT_OBJECT) {
if (key) {
if (ZSTR_VAL(key)[0] == '\0' && ZSTR_LEN(key) > 0 && Z_TYPE_P(val) == IS_OBJECT) {
//跳過受保護的屬性和私有屬性
/* Skip protected and private members. */
continue;
}
//need_comma初始值是0
if (need_comma) {
smart_str_appendc(buf,');
} else {
need_comma = 1;
}
php_json_pretty_print_char(buf,'\n');
php_json_pretty_print_indent(buf,encoder);
// 處理字串屬性的key(例如判斷key中的中文或者特殊字元的處理)
if (php_json_escape_string(buf,ZSTR_VAL(key),ZSTR_LEN(key),options & ~PHP_JSON_NUMERIC_CHECK,encoder) == FAILURE &&
(options & PHP_JSON_PARTIAL_OUTPUT_ON_ERROR) &&
buf->s) {
ZSTR_LEN(buf->s) -= 4;
smart_str_appendl(buf,"\"\"",2);
}
} else {
if (need_comma) {
smart_str_appendc(buf,');
} else {
newww.cppcns.comed_comma = 1;
}
php_json_pretty_print_char(buf,encoder);
smart_str_appendc(buf,'"');
smart_str_append_long(buf,(zend_long) index);
smart_str_appendc(buf,'"');
}
smart_str_appendc(buf,':');
php_json_pretty_print_char(buf,' ');
}
// ↑ end 從這裡之前都是判斷key怎麼處理以及元素末尾怎麼處理 ↑↑↑↑
//繼續呼叫對普通元素編碼的 php_json_encode_zval() (實現陣列和物件的遞迴閉環)
if (php_json_encode_zval(buf,data,encoder) == FAILURE &&
!(options & PHP_JSON_PARTIAL_OUTPUT_ON_ERROR)) {
PHP_JSON_HASH_APPLY_PROTECTION_DEC(myht);
return FAILURE;
}
} ZEND_HASH_FOREACH_END();
}
PHP_JSON_HASH_APPLY_PROTECTION_DEC(myht);
// 當前深度是否到達了設定的最大深度(預設512)
if (encoder->depth > encoder->max_depth) {
encoder->error_code = PHP_JSON_ERROR_DEPTH;
if (!(options & PHP_JSON_PARTIAL_OUTPUT_ON_ERROR)) {
return FAILURE;
}
}
--encoder->depth;
/* Only keep closing bracket on same line for empty arrays/objects */
if (need_comma) {
php_json_pretty_print_char(buf,'\n');
php_json_pretty_print_indent(buf,encoder);
}
if (r == PHP_JSON_OUTPUT_ARRAY) {
smart_str_appendc(buf,']');
} else {
smart_str_appendc(buf,'}');
}
return SUCCESS;
}
/* }}} */
分析
看了原始碼,我得出了一些結論。
- 只有 null,布林值,浮點數,整數,字串才會被直接編碼
- 物件要麼實現 JsonSerializable 並定義一個 jsonSerialize() ,要麼就被當成一個數組,只會被處理公開非靜態屬性
- json_encode() 並不會直接編碼陣列和物件,而是會遞迴遍歷出所有可遍歷的元素,並處理 key
- 原始碼中 php_json_encode_zval() 和 php_json_encode_array() 的相互呼叫,實現了陣列和物件遍歷的閉環
- 引用不會被編碼
另外,關於 json_encode() 的 options ,我覺得這裡處理的技巧非常有趣,巧妙利用位運算來區別多個常量,有興趣的慢慢看看研究研究。(提示,將 options 每個常量轉成二進位制來看,json_encode() 接受多個 option 是按位或 | )
Demo
>>> $a = [1,2,3,4];
=> [
1,4,]
>>> json_encode($a);
=> "[1,4]"
>>> json_encode((object)$a);
=> "{"0":1,"1":2,"2":3,"3":4}"
>>> json_encode($a,JSON_FORCE_OBJECT);
=> "{"0":1,JSON_FORCE_OBJECT|JSON_PRETTY_PRINT);程式設計客棧
=> """
{\n
"0": 1,\n
"1": 2,\n
"2": 3,\n
"3": 4\n
}
"""
$arr = array(
'0'=>'a','1'=>'b','2'=>'c','3'=>'d'
);
echo json_encode($arr);
但是結果是
["a","b","c","d"]
需求是要返回JSON物件,是這樣似的
{"0":"a","1":"b","2":"c","3":"d"}
You can do it,you nee add
$arr = array(
'0'=>'a','3'=>'d'
);
echo json_encode((object)$arr);
輸出結果
{"0":"a","3":"d"}
以上就是原始碼分析系列之json_encode()如何轉化一個物件的詳細內容,更多關於原始碼json_encode()的資料請關注我們其它相關文章!
