首页 > 解决方案 > 如何将 Laravel Http 响应作为 json 对象而不是数组返回?

问题描述

我正在使用 Laravel Http Client 从 Microsoft Graph API 获取用户集合。我的代码如下:

public function index()
    {
        $response = Http::withToken($this->accessToken)
                        ->get('https://graph.microsoft.com/v1.0/users');
        foreach($response['value'] as $user)
        {
            echo $user['displayName'] . '<br/>';
        }
    }

但是,我希望能够访问用户详细信息,例如:

public function index()
    {
        $response = Http::withToken($this->accessToken)
                        ->get('https://graph.microsoft.com/v1.0/users');
        foreach($response->value as $user)
        {
            echo $user->displayName . '<br/>';
        }
    }

我该怎么办?

更新

public function index()
    {
        $response = Http::withToken($this->accessToken)
                        ->get('https://graph.microsoft.com/v1.0/users')
                        ->throw();
        $users = $response->object();
        foreach($users->value as $user)
        {
            echo $user->displayName . '<br/>';
        }
    }

标签: phplaravel

解决方案


试试下面的代码它工作正常。

public function index()
{
    $response = Http::withToken($this->accessToken)
                    ->get('https://graph.microsoft.com/v1.0/users');            
    $response = $response->object();
    foreach($response->value as $user)
    {
        echo $user->displayName . '<br/>';
    }
}

或者

public function index()
{
    $response = Http::withToken($this->accessToken)
                    ->get('https://graph.microsoft.com/v1.0/users');
    $response = json_decode(json_encode($response->json()));
    foreach($response->value as $user)
    {
        echo $user->displayName . '<br/>';
    }
}

或者

public function index()
{
    $response = Http::withToken($this->accessToken)
                    ->get('https://graph.microsoft.com/v1.0/users');
    $response = (object) $response->json();
    foreach($response->value as $user)
    {
        echo $user->displayName . '<br/>';
    }
}

推荐阅读