
DsStack::jsonSerialize 함수는 PHP 7.4 이상에서 사용할 수 있는 함수입니다. 중첩된 구조의 데이터를 JSON 형식으로 변환할 때, jsonSerialize 함수는 객체의 프로퍼티를 자동으로 처리하지 않습니다.
따라서, 중첩된 구조의 데이터를 JSON 형식으로 변환하려면, jsonSerialize 함수를 오버라이딩하여 필요한 프로퍼티를 처리해야 합니다.
예를 들어, 위의 예시에서 User 클래스의 address 프로퍼티가 중첩된 구조인 Address 클래스의 인스턴스를 참조하고 있습니다. jsonSerialize 함수를 오버라이딩하여 address 프로퍼티를 처리할 수 있습니다.
#hostingforum.kr
php
class User implements JsonSerializable {
public $id;
public $name;
public $address;
public function __construct($id, $name, Address $address) {
$this->id = $id;
$this->name = $name;
$this->address = $address;
}
public function jsonSerialize() {
return [
'id' => $this->id,
'name' => $this->name,
'address' => $this->address->jsonSerialize()
];
}
}
class Address implements JsonSerializable {
public $street;
public $city;
public $country;
public function __construct($street, $city, $country) {
$this->street = $street;
$this->city = $city;
$this->country = $country;
}
public function jsonSerialize() {
return [
'street' => $this->street,
'city' => $this->city,
'country' => $this->country
];
}
}
$user = new User(1, 'John Doe', new Address('123 Main St', 'Anytown', 'USA'));
$json = json_encode($user, JSON_PRETTY_PRINT);
print($json);
위의 예시에서, User 클래스와 Address 클래스는 JsonSerializable 인터페이스를 구현하고 있습니다. jsonSerialize 함수를 오버라이딩하여 address 프로퍼티를 처리하였습니다. jsonSerialize 함수는 객체의 프로퍼티를 JSON 형식으로 변환하고, 중첩된 구조의 데이터도 자동으로 처리합니다.
결과적으로, jsonSerialize 함수를 오버라이딩하여 address 프로퍼티를 처리하면, 중첩된 구조의 데이터를 JSON 형식으로 변환할 수 있습니다.
2025-05-17 03:13