'How to convert a json response into a callable object in php?
I'm trying to convert the json response below in $response
variable to a callable function like $response->getStatus()
so it can return failed
.
Here's the response
$response = '{
"status": "failed",
"msg": {
"success": true,
"license": "invalid_item_id",
"license_limit": 2,
"site_count": 2,
"activations_left": 0,
"price_id": false
}
}'
I found something about using LazyJsonMapper. Please how can I go about it. Thanks
Solution 1:[1]
EDIT:
I recently discovered you can use stdClass()
to get the effect you want that is similar to an array:
<?php
$stdClass = new stdClass();
$stdClass->var1 = "Example of stdClass()";
$stdClass->var2 = "Another Example";
$stdClass->HelloWorld = "Hello World!";
# Just like array you can do:
print_r($stdClass);
# Or do this:
foreach($stdClass as $std){
echo $std, PHP_EOL;
}
# Just access the variable the same way you declared it:
echo $stdClass->HelloWorld;
SandBox for example: https://sandbox.onlinephpfunctions.com/c/e1f5a
OLD:
You can use the extract function to basically get what you want, like so:
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
Live Demo: http://sandbox.onlinephpfunctions.com/code/b1e70ff642e93d77d85bd9780ecf5d9fa8f88819
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |