当我想在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
];
}
我该如何解决这个问题?
答案 0 :(得分:0)
从控制器返回JSON时,您可以使用setEncodingOptions
进行操作:
class MyController {
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);
}
}
答案 1 :(得分:0)
尝试在“ 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);
}