在 API 资源 laravel 中使用 JSON_UNESCAPED_UNICODE

moh*_*mad 6 php laravel

当我想返回 api 资源中的文本时,得到以下响应:

\n\n
{"data":{"message":"\\u\xdb\xb0\xdb\xb6\xdb\xb3\xdb\xb3\\u\xdb\xb0\xdb\xb6\xdb\xb4\xdb\xb4\\u\xdb\xb0\xdb\xb6\xdb\xb2\xdb\xb7\\u\xdb\xb0\xdb\xb6\xdb\xb4\xdb\xb5 \\u\xdb\xb0\xdb\xb6\xdb\xb2\xdb\xb8\\u\xdb\xb0\xdb\xb6\xdb\xb3\xdb\xb1 \\u\xdb\xb0\xdb\xb6\xdb\xb2a\\u\xdb\xb0\xdb\xb6\xdb\xb4\xdb\xb8"},"status":\xdb\xb0}\n
Run Code Online (Sandbox Code Playgroud)\n\n

response()->json当我将以下代码添加到响应中时,这个问题得到了解决:

\n\n

return 200, [], JSON_UNESCAPED_UNICODE

\n\n

喜欢:

\n\n
return response()->json([\'message\' => \'my utf8 text\'], 200, [], JSON_UNESCAPED_UNICODE);\n
Run Code Online (Sandbox Code Playgroud)\n\n

但在 api 资源中我无法将此代码添加到响应中

\n\n

api资源代码:

\n\n
    public function toArray($request) {\n        return [\n            \'id\' => $this->id,\n            \'userId\' => $this->user_id,\n            \'title\' => $this->title,\n            \'text\' => $this->text,\n            \'isAccepted\' => $this->is_accepted,\n            \'viewCount\' => $this->view_count,\n            \'likeCount\' => $this->like_count,\n            \'dislikeCount\' => $this->dislike_count,\n            \'commentCount\' => $this->comment_count,\n            \'createdAt\' => date(\'Y-m-d H:i:s\' , strtotime($this->created_at)),\n        ];\n    }\n\n    public function with($request) {\n        return [\n          \'status\' => Status::SUCCESS\n        ];\n    }\n
Run Code Online (Sandbox Code Playgroud)\n\n

我该如何解决这个问题?

\n

小智 -1

尝试在“Illuminate\Http\JsonResponse.php”中编辑以下函数

public function __construct($data = null, $status = 200, $headers = [], $options = 0)
{
    $headers = ['Content-Type' => 'application/json; charset=UTF-8',
        'charset' => 'utf-8'];
    $options = JSON_UNESCAPED_UNICODE;
    $this->encodingOptions = $options;

    parent::__construct($data, $status, $headers);
}
Run Code Online (Sandbox Code Playgroud)

  • 我的意思是,一个**可以**编辑库类,但它最终会弄巧成拙,因为它要求每次“composer install”或“c​​omposer update”时都执行相同的操作。我认为更好的解决方案是在应用程序中添加配置或覆盖库行为的代码。 (4认同)