首页 > 解决方案 > 如何将 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 的信息。请问我该怎么做。谢谢

标签: phparraysjsonclassobject

解决方案


您可以使用 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


推荐阅读