将JSON字符串转换为可用的PHP类对象

时间:2019-07-02 17:31:29

标签: php json class

我有一个使用以下代码行转换为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和主题值?

任何帮助或想法都将不胜感激-马克

2 个答案:

答案 0 :(得分:1)

我相信您有一个名为02-Jul-2019 16:47:00 UTC的密钥以及其中的一个子数组。
我认为键名是动态的,因此不能对其进行硬编码。
因此,foreach对象并回显子数组项。

foreach($stdResponse as $response){
    echo $response['uuid'];
    //echo $response['id'];
    //echo $response['topic'];
}

答案 1 :(得分:0)

我想提供一个替代解决方案。

从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);
  }    
}

不涉及魔术(这是一件好事)