php - 在 API 资源 laravel 中使用 JSON_UNESCAPED_UNICODE
问题描述
当我想在 api 资源中返回文本时,得到以下响应:
{"data":{"message":"\u۰۶۳۳\u۰۶۴۴\u۰۶۲۷\u۰۶۴۵ \u۰۶۲۸\u۰۶۳۱ \u۰۶۲a\u۰۶۴۸"},"status":۰}
response()->json
当我将以下代码添加到响应时,此问题已解决:
return 200, [], JSON_UNESCAPED_UNICODE
喜欢:
return response()->json(['message' => 'my utf8 text'], 200, [], JSON_UNESCAPED_UNICODE);
但在 api 资源中我无法将此代码添加到响应中
api资源代码:
public function toArray($request) {
return [
'id' => $this->id,
'userId' => $this->user_id,
'title' => $this->title,
'text' => $this->text,
'isAccepted' => $this->is_accepted,
'viewCount' => $this->view_count,
'likeCount' => $this->like_count,
'dislikeCount' => $this->dislike_count,
'commentCount' => $this->comment_count,
'createdAt' => date('Y-m-d H:i:s' , strtotime($this->created_at)),
];
}
public function with($request) {
return [
'status' => Status::SUCCESS
];
}
我该如何解决这个问题?
解决方案
您可以setEncodingOptions
在从控制器返回 JSON 时使用:
use Illuminate\Support\Facades\Response;
class MyController extends Controller {
public function index() {
$myJsonStructure = [
'data' => '۶۲۷۶۴۸',
];
// SET the bit flag in the encoding options
// (default encoding options are:
// JSON_HEX_TAG | JSON_HEX_APOS | JSON_HEX_AMP | JSON_HEX_QUOT = 15)
$response = Response::json($myJsonStructure);
return $response->setEncodingOptions(
$response->getEncodingOptions() | JSON_UNESCAPED_UNICODE
);
// -OR- replace all encoding options with a set of my choosing
return Response::json($myJsonStructure)
->setEncodingOptions(JSON_UNESCAPED_UNICODE | JSON_HEX_AMP);
}
}
推荐阅读
- android - 如何将 python flask-html 服务器(pythonanywhere)中的数据交换到 AndroidStudio 应用程序?
- c - 变量的编译时初始化如何在c内部工作?
- azure - 使用 Azure AD-App (OAuth2) 访问 Microsoft API
- python - 如何从另一个数据框创建新的数据框?
- nlp - “常规”英语单词列表
- uwp - 如何为 uwp 应用程序创建 .exe/.msi
- groovy - 如何在 groovy 安装期间修复错误
- android - android 9 Pie中的凌空SSLHandshakeException
- c# - 如何为 Azure Functions 配置 NLog?
- java - 在java中的数字后添加空格