在Controller 层我直接调用了别人的方法,他返回的是JsonResponse对象。我就想拿到其中的数据,引起了我错误的做法。
//别人的方法
public function testJsonResponse(Request $request) {
$data = [];
$data['messsage'] = "hello";
return response()->json($data);
}
public function getJson(Request $request){
$result = $this->testJsonResponse($request); //想在此获得别人的json数据
var_dump($result);
}
然后由postman访问getJson如下:
object(Illuminate\Http\JsonResponse)#180 (11) {
["data":protected]=>
string(20) "{"messsage":"hello"}"
["content":protected]=>
string(20) "{"messsage":"hello"}"
["version":protected]=>
string(3) "1.0"
["statusCode":protected]=>
int(200)
["statusText":protected]=>
string(2) "OK"
["charset":protected]=>
NULL
["original"]=>
array(1) {
["messsage"]=>
string(5) "hello"
}
["exception"]=>
NULL
}
最开始:看到data里面就是数据就想直接拿
然后写法是
$result.data
此处犯了两个错误,第一个当然是语法错误了,还有一个是作用域的错误。
PHP中访问对象的属性和方法都用 ->,由于使用Java的习惯,用.作为调用的习惯。
另外就是protected作用域的问题,该属性或者方法仅在自身或者子类中可用。
然后是查看文档
https://laravel.com/api/4.2/Illuminate/Http/JsonResponse.html
可以调用getData进行获取数据
mixed getData(bool $assoc = false, int $depth = 512)
//设置$assoc为true 返回数组类型,false默认返回对象
$jsonArray = $result->getData(true);
//当然也可以直接获取这是我后来测试出来的
$result->original