php中操作json的函数有json_encode()
,json_decode()
在该文档中,encode的传入值可以是除了resource 类型之外的任何数据类型。
class Siam{
public $name = 'siam';
protected $age = 21;
private $sex = "男";
public static $lover = "undefined";
public function test()
{
return "??";
}
}
echo json_encode(new Siam());
// 得到 {"name":"siam"}
默认的json_encode,只能序列化类中的public属性。
php还提供了一个自定义类序列化的接口,JsonSerializable
实现 JsonSerializable 的类可以 在 json_encode() 时定制他们的 JSON 表示法。
JsonSerializable {
/* 方法 */
abstract public jsonSerialize ( void ) : mixed
}
需要实现的方法jsonSerialize(),它的返回值:
返回能被 json_encode() 序列化的数据, 这个值可以是除了 resource 外的任意类型。
class Siam implements JsonSerializable
{
public $name = 'siam';
protected $age = 21;
private $sex = "男";
public static $lover = "undefined";
public function test()
{
return "??";
}
public function jsonSerialize()
{
return [
'name' => $this->name,
'age' => $this->age,
'lover'=> self::$lover
];
}
}
echo json_encode(new Siam());
// 得到 {"name":"siam","age":21,"lover":"undefined"}
当我们定义一些类的时候,它们经常参与json序列化和传输,同时默认的public属性序列化不能满足,我们就可以自定义序列化接口,提供我们想要的数据。
扫码关注腾讯云开发者
领取腾讯云代金券
Copyright © 2013 - 2025 Tencent Cloud. All Rights Reserved. 腾讯云 版权所有
深圳市腾讯计算机系统有限公司 ICP备案/许可证号:粤B2-20090059 深公网安备号 44030502008569
腾讯云计算(北京)有限责任公司 京ICP证150476号 | 京ICP备11018762号 | 京公网安备号11010802020287
Copyright © 2013 - 2025 Tencent Cloud.
All Rights Reserved. 腾讯云 版权所有