json 序列化接口jsonserializable
实现 jsonserializable 的类可以 在 json_encode() 时定制他们的 json 表示法。
jsonserializable::jsonserialize — 指定需要被序列化成 json 的数据
example #1 返回一个数组
<?php class arrayvalue implements jsonserializable { public function __construct(array $array) { $this->array = $array; } public function jsonserialize() { return $this->array; } } $array = [1, 2, 3]; echo json_encode(new arrayvalue($array), json_pretty_print); ?>
以上例程会输出:
[ 1, 2, 3 ]
example #2 返回了一个关联数组
<?php class arrayvalue implements jsonserializable { public function __construct(array $array) { $this->array = $array; } public function jsonserialize() { return $this->array; } } $array = ['foo' => 'bar', 'quux' => 'baz']; echo json_encode(new arrayvalue($array), json_pretty_print); ?>
以上例程会输出:
{ "foo": "bar", "quux": "baz" }
example #3 返回一个整型数字
<?php class integervalue implements jsonserializable { public function __construct($number) { $this->number = (integer) $number; } public function jsonserialize() { return $this->number; } } echo json_encode(new integervalue(1), json_pretty_print); ?>
以上例程会输出:
1
example #4 返回一个字符串
<?php class stringvalue implements jsonserializable { public function __construct($string) { $this->string = (string) $string; } public function jsonserialize() { return $this->string; } } echo json_encode(new stringvalue('hello!'), json_pretty_print); ?>
以上例程会输出:
hello!
json 函数
json_decode — 对 json 格式的字符串进行编码
json_encode — 对变量进行 json 编码
json_last_error_msg — returns the error string of the last json_encode() or json_decode() call
json_last_error — 返回最后发生的错误
