laravel使用Dingo\Api写接口跟android对接时,android一直反应解析错误,无法解析数据。
{
"status_code":200,"message":"请求成功","data":[
{
"type":2,"message_id":1383,"title":"视频点赞","content":"赞了你的视频","created":1565922723,"user_id":56,"user_nickname":"阿葛","message_url":"","video_info":[
]
},{
"type":2,"message_id":1338,"title":"评论点赞","content":"赞了你的评论","created":1565784398,"user_id":41,"user_nickname":"阿城","video_info":{
"id":3214,"title":"好一个如来神掌满分?!","cover":[],"dynamic_cover":[],"play_url":"","play_times":15034,"play_count":676,}
}
]
}
由于 video_info 没有找到,直接返回的 new stdClass(),希望能返回 空对象, 但是,到 response()->json() 时 ,直接变成了空数组。
因为使用 Dingo\Api 时,会有不同的响应处理,有时候,会通过 \Dingo\Api\Http\Response::makeFromJson 解码内容,然后创建新实例,把 {} 变成了 []。
这里我们手动处理返回的数据。
function returnJson($data = [],$code = '',$message = '')
{
$result = [
'status_code' => $code,'message' => $message,'data' => $data,];
//手动编码,避免dingo/api把空对象转成空数组
$result = json_encode($result,JSON_UNESCAPED_UNICODE);
return response()->json($result);
}
原文链接:https://www.f2er.com/laravel/539086.html