1、问题描述
Laravel中返回的json默认对中文进行unicode编码,如果部分互联系统不接收unicode,如何解决?
- 实际操作中发现
Laravel自身的Controller和使用了Dingo的Controller-API处理方式也不一样
2、解决Laravel自身的Controller思路
public function common(Request $request)
{
$headers = array(
'Content-Type' => 'application/json; charset=utf-8'
);
$retData = [
'姓名' => '张三',
'birthdate' => '2010-02-15',
'性别' => '男性',
];
return \Response::json($retData, 200, $headers, JSON_UNESCAPED_UNICODE);
}
namespace App\Http\Middleware;
use Closure;
class DistSjlApiAuth
{
public function handle($request, Closure $next)
{
$data = $next($request);
if ($data instanceof \Illuminate\Http\JsonResponse) {
$data->setEncodingOptions(JSON_UNESCAPED_UNICODE);
}
return $data;
}
}
3、解决Dingo的Controller-API思路
- 重写
Json类,在配置文件config/api.php中修改formats.json项。
- 重写
Json类其实主要是重写filterJsonEncodeOptions这个方法,JsonOptionalFormatting这个trait中filterJsonEncodeOptions方法必须与[JSON_PRETTY_PRINT]取交集,改为与[JSON_PRETTY_PRINT, JSON_UNESCAPED_UNICODE,]取交集,encode方法中的$jsonEncodeOptions加入项[JSON_UNESCAPED_UNICODE].
<?php
namespace App\Helpers\Api;
use Dingo\Api\Http\Response\Format\Format;
use Dingo\Api\Http\Response\Format\JsonOptionalFormatting;
use Illuminate\Support\Str;
use Illuminate\Contracts\Support\Arrayable;
class Json extends Format
{
use JsonOptionalFormatting;
public function formatEloquentModel($model)
{
$key = Str::singular($model->getTable());
if (! $model::$snakeAttributes) {
$key = Str::camel($key);
}
return $this->encode([$key => $model->toArray()]);
}
public function formatEloquentCollection($collection)
{
if ($collection->isEmpty()) {
return $this->encode([]);
}
$model = $collection->first();
$key = Str::plural($model->getTable());
if (! $model::$snakeAttributes) {
$key = Str::camel($key);
}
return $this->encode([$key => $collection->toArray()]);
}
public function formatArray($content)
{
$content = $this->morphToArray($content);
array_walk_recursive($content, function (&$value) {
$value = $this->morphToArray($value);
});
return $this->encode($content);
}
public function getContentType()
{
return 'application/json';
}
protected function morphToArray($value)
{
return $value instanceof Arrayable ? $value->toArray() : $value;
}
protected function encode($content)
{
$jsonEncodeOptions = [JSON_UNESCAPED_UNICODE];
if ($this->isJsonPrettyPrintEnabled()) {
$jsonEncodeOptions[] = JSON_PRETTY_PRINT;
}
$encodedString = $this->performJsonEncoding($content, $jsonEncodeOptions);
if ($this->isCustomIndentStyleRequired()) {
$encodedString = $this->indentPrettyPrintedJson(
$encodedString,
$this->options['indent_style']
);
}
return $encodedString;
}
protected function filterJsonEncodeOptions(array $jsonEncodeOptions)
{
return array_intersect($jsonEncodeOptions, [JSON_PRETTY_PRINT, JSON_UNESCAPED_UNICODE,]);
}
}