欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

源码分析系列之json_encode()如何转化一个对象

程序员文章站 2022-07-08 23:40:07
json_encode()如何转化一个对象? 使用 json_encode() 将数组 array 转化成 json 字符串我们都已经很熟悉...

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());

输出

{ "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
}

可以看出 php 版本低于 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, zval *val, 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, val, options, &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, zval *val, int options, 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), options, encoder);
		case is_object:
            // 如果对象实现了jsonserializable,就将对象中的jsonserialize()返回的结果进行编码
			if (instanceof_function(z_objce_p(val), php_json_serializable_ce)) {
				return php_json_encode_serializable_object(buf, val, options, encoder);
			}
            // 如果对象没有实现了jsonserializable,就执行下边的这个php_json_encode_array()
			/* fallthrough -- non-serializable object */
		case is_array:
            // 解析数组
			return php_json_encode_array(buf, val, options, 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, "null", 4);
			}
			return failure;
	}
	return success;
}
/* }}} */

php_json_encode_array()

这个函数递归编码数组及没有实现jsonserializable()的对象(只编码对象的公开属性)

static int php_json_encode_array(smart_str *buf, zval *val, int options, 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, "null", 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) {
					smart_str_appendc(buf, ',');
				} else {
					need_comma = 1;
				}
				//这两个方法是option中有json_pretty_print的时候才会执行的
				php_json_pretty_print_char(buf, options, '\n');
				php_json_pretty_print_indent(buf, options, 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, options, '\n');
					php_json_pretty_print_indent(buf, options, 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 {
						need_comma = 1;
					}
					php_json_pretty_print_char(buf, options, '\n');
					php_json_pretty_print_indent(buf, options, 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, options, ' ');
			}
			// ↑ end 从这里之前都是判断key怎么处理以及元素末尾怎么处理  ↑↑↑↑
            //继续调用对普通元素编码的 php_json_encode_zval() (实现数组和对象的递归闭环)
			if (php_json_encode_zval(buf, data, options, 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, options, '\n');
		php_json_pretty_print_indent(buf, options, 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,
     2,
     3,
     4,
   ]
>>> json_encode($a);
=> "[1,2,3,4]"
>>> json_encode((object)$a);
=> "{"0":1,"1":2,"2":3,"3":4}"
>>> json_encode($a,json_force_object);
=> "{"0":1,"1":2,"2":3,"3":4}"
>>> json_encode($a,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','1'=>'b','2'=>'c','3'=>'d'
);
echo json_encode((object)$arr);

输出结果

{"0":"a","1":"b","2":"c","3":"d"}

以上就是源码分析系列之json_encode()如何转化一个对象的详细内容,更多关于源码json_encode()的资料请关注其它相关文章!