php - 如何将 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/>';
}
}
解决方案
试试下面的代码它工作正常。
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/>';
}
}
推荐阅读
- cassandra - 副本数据中心的 Cassandra 目录设置
- sql-server - 为什么我的应用用户找不到始终加密的证书?
- javascript - AJAX 之后的 Kendo DropDownList 选择值
- amazon-web-services - 设置“maxActiveInstances”错误
- java - Android Studio 3.1.2 中的 Gradle 同步失败
- java - 用于 IntelliJ 多线程测试的 Java 工具
- reactjs - Reactjs没有更新任何东西
- java - 解析一个json文件丢失的数据结构 - JAVA
- objective-c - 未设置邮件帐户时应用程序崩溃
- java - 点燃队列是否有一些方法来检查队列是否创建,就像缓存一样