php - 如何将 json 响应转换为 php 中的可调用对象?
问题描述
我正在尝试将$response
变量中的 json 响应转换为可调用函数,例如$response->getStatus()
它可以返回failed
。
这是回应
$response = '{
"status": "failed",
"msg": {
"success": true,
"license": "invalid_item_id",
"license_limit": 2,
"site_count": 2,
"activations_left": 0,
"price_id": false
}
}'
我发现了一些关于使用 LazyJsonMapper 的信息。请问我该怎么做。谢谢
解决方案
您可以使用 extract 函数基本上得到您想要的,如下所示:
class status{
private $json;
public $getStatus;
public $getMsg;
public function __construct(){
$this->json = '{
"status": "failed",
"msg": {
"success": false,
"license": "invalid_item_id",
"license_limit": 2,
"site_count": 2,
"activations_left": 0,
"price_id": false
}
}';
$array = json_decode($this->json, true);
extract($array);
$this->getStatus = $status;
$this->getMsg = $msg;
}
# If you want your parentheses you can just do this
public function getStatus(){
return $this->getStatus;
}
}
$s = new status;
print_r( $s->getStatus().PHP_EOL );
print_r( $s->getStatus.PHP_EOL );
print_r( $s->getMsg['license_limit'].PHP_EOL );
print_r( $s->getMsg['license'].PHP_EOL );
# Results:
#
# failed
# failed
# 2
# invalid_item_id
现场演示:http ://sandbox.onlinephpfunctions.com/code/b1e70ff642e93d77d85bd9780ecf5d9fa8f88819
推荐阅读
- sql - 数组 json 将元素拆分为列 postgres
- javascript - 将 react-dropzone 添加到 react-16.13.1 项目时出现问题
- spring - 在 Spring 中将查询参数映射到对象中的名称别名
- ruby-on-rails - 如何在 Ruby on Rails 上上传和显示图像而不存储它们?
- sql-server - 如何添加计算列:子查询返回超过 1 个值
- ios - WebView 退出时注销帐户/清除导航
- javascript - 如何使用 node.js 修改我的 HTML 文件?
- javascript - 如何正确处理 ASP.NET Core MVC 中的 AJAX 错误?
- azure-ad-b2c - 在 Azure AD B2C 自定义策略中调用 api 以进行邮政地址验证
- flutter - 如何处理具有相同动画的大量元素?