[英]Converting a JSON string into a usable PHP class object
我有一個使用以下代碼行轉換為stdObject的JSON字符串:
$stdResponse = json_decode($jsonResponse);
這給了我這個對象:
[02-Jul-2019 16:47:00 UTC] stdClass Object
(
[uuid] => qj/VA9z2SZKF6bT5FboOWf#$
[id] => 653070384
[topic] => Mark Test Meeting
)
現在,我想訪問該對象的成員,例如UUID。 我試過只是做$ stdResponse-> uuid,但這是一個錯誤。
然后,我嘗試使用此PHP類將stdObject轉換為我真正想要的對象:
class zoom_meeting
{
public $uuid;
public $id;
public $topic;
public function getUUID()
{
return ($this->uuid);
}
public function getMeetingId()
{
return ($this->id);
}
public function getMeetingName()
{
return ($this->topic);
}
}
我通過使用以下代碼行和在此論壇上其他地方發現的“ cast”函數(根據評論似乎有效)做到了這一點:
$castMeeting = cast($stdResponse, "zoom_meeting");
函數強制轉換的位置是:
function cast($instance, $className)
{
return unserialize(sprintf(
'O:%d:"%s"%s',
strlen($className),
$className,
strstr(strstr(serialize($instance), '"'), ':')
));
}
看起來很有效。 現在是對象:
[02-Jul-2019 16:47:00 UTC] CASTED MEETING:
[02-Jul-2019 16:47:00 UTC] zoom_meeting Object
(
[uuid] => qj/VA9z2SZKF6bT5FboOWf#$
[id] => 653070384
[topic] => Mark Test Meeting
)
然后,我嘗試使用get方法從此類對象中“獲取”所需的信息,這是每個調用的輸出:
error_log(print_r($castMeeting->getUUID(), true));
[02-Jul-2019 16:47:00 UTC] 1
error_log(print_r($castMeeting->getMeetingId(), true));
[02-Jul-2019 16:47:00 UTC] 1
error_log(print_r($castMeeting->getMeetingName(), true));
[02-Jul-2019 16:47:00 UTC] 1
只是“ 1”就是這樣。 顯然,我沒有得到我期望的數據。 誰能告訴我這里出了什么問題? 是否有更好/更清潔的方法來獲取uuid,id和topic值?
任何幫助或想法將不勝感激-馬克
我相信您有一個名為02-Jul-2019 16:47:00 UTC
的密鑰以及其中的一個子02-Jul-2019 16:47:00 UTC
。
我假設鍵名是動態的,因此硬編碼不是一個選擇。
因此,foreach對象並回顯子數組項。
foreach($stdResponse as $response){
echo $response['uuid'];
//echo $response['id'];
//echo $response['topic'];
}
我想提供一個替代解決方案。
從json進行的轉換可以是您的類上的顯式方法。 我稱其為“命名構造函數”。
class zoom_meeting
{
private $uuid;
private $id;
private $topic;
public function __construct($uuid, $meetingid, string $meetingname)
{
$this->uuid = $uuid;
$this->meetingid = $meetingid;
$this->topic = $meetingname;
}
public static function fromJSON(string $json): self
{
$data = json_decode($json);
return new self($data->uuid, $data->meetingid, $data->meetingname);
}
public function getUUID()
{
return ($this->uuid);
}
public function getMeetingId()
{
return ($this->id);
}
public function getMeetingName()
{
return ($this->topic);
}
}
不涉及任何魔術(這是一件好事)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.