让自定义类实现 JsonSerializable 接口并返回数组,即可在 json_encode() 时自动转为 JSON 字符串。

核心原理与数据映射
JsonSerializable 是 PHP 提供的标准接口,强制要求类定义 jsonSerialize() 方法。该方法必须返回一个可以被 json_encode 处理的值(通常是关联数组)。当对象被序列化时,引擎会调用此方法获取数据源,从而绕过默认的私有/受保护属性过滤机制。

默认情况下,PHP 的 json_encode 只能访问对象的公有属性。对于封装良好的类,私有或受保护字段会被忽略。通过实现该接口,开发者可以精确控制哪些字段参与序列化,以及它们的键名和格式。例如,可以将内部的日期对象转换为 ISO 8601 字符串,或将嵌套的对象递归序列化为数组结构。
完整实现示例与运行
创建一个包含私有属性的类,实现 JsonSerializable 接口,并在 jsonSerialize 中组装返回数据。将代码保存为 user.php,在命令行执行 php user.php 查看输出。

<?php
class Address {
private string $city;
private string $zip;
public function __construct(string $city, string $zip) {
$this->city = $city;
$this->zip = $zip;
}
public function jsonSerialize(): array {
return [
'city' => $this->city,
'zip' => $this->zip,
];
}
}
class User implements JsonSerializable {
private string $name;
private int $age;
private ?Address $address;
public function __construct(string $name, int $age, ?Address $address = null) {
$this->name = $name;
$this->age = $age;
$this->address = $address;
}
public function jsonSerialize(): array {
$data = [
'name' => $this->name,
'age' => $this->age,
];
if ($this->address !== null) {
$data['address'] = $this->address->jsonSerialize();
}
return $data;
}
}
$user = new User('Alice', 30, new Address('Beijing', '100000'));
echo json_encode($user, JSON_PRETTY_PRINT);
程序输出标准的 JSON 格式字符串,包含 name、age 和嵌套的 address 对象。若传入 null 地址,则输出中不包含 address 键。这验证了接口方法对数据结构的完全控制权。
以下代码展示了如何处理普通字段、计算字段以及嵌套对象。注意 jsonSerialize 返回的数组键名将直接成为 JSON 对象的键。
处理嵌套对象与空值策略
当类中包含其他实现了 JsonSerializable 的对象时,需确保内部对象也正确实现了接口,否则会被转为空对象 {}。可通过检查属性是否为 null 来决定是否包含该键,以精简输出。
若内部对象未实现接口,json_encode 无法提取其数据。建议在业务逻辑层统一处理依赖注入或初始化,确保所有参与序列化的对象都具备序列化能力。对于可选字段,仅在值不为 null 时加入返回数组,避免生成无意义的 null 键值对。