【问题标题】:response()->json unable to decode in Laravel [closed]response()->json 无法在 Laravel 中解码 [关闭]
【发布时间】:2020-03-13 16:43:41
【问题描述】:

我们使用的是 Laravel 5.* 我们不想在我们的项目中更改此代码 响应()->json

它将反映整个应用程序,这太可怕了。所以我们需要一个合适的解决方案,我在这个问题的 cmets 中找到了解决方案。 谢谢。

这里是场景:

$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

【问题讨论】:

  • 那么,你还有什么问题?
  • 尝试返回json_encode(['code' => 1, 'message' => 'Content-type is ABC', 'data' => ['code'=>1,'message'=>'Content-type is ABC'] ]);
  • this post 而言,您应该可以打印它。
  • 您的回复为空,这就是原因
  • dd($response->getContent()); 将打印 json 响应

标签: php json laravel


【解决方案1】:

尝试使用

$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"}}"

【讨论】:

  • OP 确实得到了正确的响应,正如他在最后一行中提到的 return $response; //You will get proper json response in function return.
  • 两者都会给出正确的 json 响应
  • OP 确实得到了响应,但他想知道为什么 dd($response); 打印 null。
  • No..dd($response) 显示的是 json 对象。但 json_decode($response) 显示为空。
  • 帖子里写的是dd($response); // print Null,但return $response; //You will get proper json response in function return.
【解决方案2】:

尝试 getContent():

echo $response->getContent();

【讨论】:

    【解决方案3】:
     $response =  response()->json(['code' => 1,
                        'message' => 'Content-type is ABC',
                        'data' => ['code'=>1,'message'=>'Content-type is ABC']
                    ]);
    

    您可以直接打印

    echo $response->getContent()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-22
      • 2013-02-16
      • 2015-08-28
      相关资源
      最近更新 更多