首页 > 解决方案 > 在 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
        ];
    }

我该如何解决这个问题?

标签: phplaravel

解决方案


您可以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);
    }
}

推荐阅读