response()-> json无法在Laravel中解码

时间:2019-11-18 10:25:51

标签: php json laravel

我们正在使用Laravel版本5. * 我们不想在我们的项目中更改此代码 response()-> json

它将反映整个应用程序,这很糟糕。因此,我们需要一个适当的解决方案,而我在此问题的评论中找到了解决方案。 谢谢。

这是场景:

$response = response()->json(['code' => 1,
    'message' => 'Content-type is ABC',
    'data' => ['code'=>1,'message'=>'Content-type is ABC']
]);

echo json_decode($response); // It always print null and nothing. 
dd($response);  // print Null
return $response; //You will get proper json response in function return.

enter image description here

3 个答案:

答案 0 :(得分:2)

尝试使用

$response =  response()->json(['code' => 1,
                    'message' => 'Content-type is ABC',
                    'data' => ['code'=>1,'message'=>'Content-type is ABC']
                ]);
$x = $response->getContent();
return $x;
OR
return $response;

输出将为

  "{"code":1,"message":"Content-type is ABC","data":{"code":1,"message":"Content-type is ABC"}}"

答案 1 :(得分:1)

尝试getContent():

echo $response->getContent();

答案 2 :(得分:0)

 $response =  response()->json(['code' => 1,
                    'message' => 'Content-type is ABC',
                    'data' => ['code'=>1,'message'=>'Content-type is ABC']
                ]);

您可以直接打印

echo $response->getContent()