1. Problem description

  • LaravelIn returnjsonThe default value is ChineseunicodeCode if part of the interconnect system does not acceptunicodeAnd how to solve it?
  • It is found in actual operationLaravelOne’s ownControllerAnd the use of theDingotheController-APIIt’s handled differently

2, solveLaravelOne’s ownControllerTrain of thought

  • Write directly in the controller
public function common(Request $request)
{
    $headers = array(
        'Content-Type'= >'application/json; charset=utf-8'
    );
    $retData = [
        'name'= >'Joe'.'birthdate'= >'2010-02-15'.'gender'= >'male',];return \Response::json($retData.200.$headers, JSON_UNESCAPED_UNICODE);
}
Copy the code
  • Write a piece of middleware that is used in a controller or routing group
namespace App\Http\Middleware;

use Closure;

class DistSjlApiAuth
{
    / * * *@desc* Handle an incoming request. * * Handle an incoming request@param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request.Closure $next)
    {
        // Other logic

        $data = $next($request);

        if ($data instanceof \Illuminate\Http\JsonResponse) {
            $data->setEncodingOptions(JSON_UNESCAPED_UNICODE);
        }

        return $data; }}Copy the code

3, solveDingotheController-APITrain of thought

  • rewriteJsonClass in the configuration fileconfig/api.phpChanges in theformats.jsonItems.
  • rewriteJsonClasses are essentially overwrittenfilterJsonEncodeOptionsThis method,JsonOptionalFormattingthistraitIn thefilterJsonEncodeOptionsMethods must be consistent with[JSON_PRETTY_PRINT]Take the intersection, change it to and[JSON_PRETTY_PRINT, JSON_UNESCAPED_UNICODE,]Take the intersection,encodeIn the method$jsonEncodeOptionsAdd item[JSON_UNESCAPED_UNICODE].

      

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
{
    /* * JSON format (as well as JSONP) uses JsonOptionalFormatting trait, which * provides extra functionality for the process of encoding data to * its JSON representation. */
    use JsonOptionalFormatting;

    /**
     * Format an Eloquent model.
     *
     * @param \Illuminate\Database\Eloquent\Model $model
     *
     * @return string
     */
    public function formatEloquentModel($model)
    {
        $key = Str::singular($model->getTable());

        if (! $model: :$snakeAttributes) {
            $key = Str::camel($key);
        }

        return $this->encode([$key= >$model->toArray()]);
    }

    /**
     * Format an Eloquent collection.
     *
     * @param \Illuminate\Database\Eloquent\Collection $collection
     *
     * @return string
     */
    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()]);
    }

    /**
     * Format an array or instance implementing Arrayable.
     *
     * @param array|\Illuminate\Contracts\Support\Arrayable $content
     *
     * @return string
     */
    public function formatArray($content)
    {
        $content = $this->morphToArray($content);

        array_walk_recursive($content.function (&$value) {
            $value = $this->morphToArray($value);
        });

        return $this->encode($content);
    }

    /**
     * Get the response content type.
     *
     * @return string
     */
    public function getContentType()
    {
        return 'application/json';
    }

    /**
     * Morph a value to an array.
     *
     * @param array|\Illuminate\Contracts\Support\Arrayable $value
     *
     * @return array
     */
    protected function morphToArray($value)
    {
        return $value instanceof Arrayable ? $value->toArray() : $value;
    }

    /**
     * Encode the content to its JSON representation.
     *
     * @param mixed $content
     *
     * @return string
     */
    protected function encode($content)
    {
        $jsonEncodeOptions = [JSON_UNESCAPED_UNICODE];

        // Here is a place, where any available JSON encoding options, that
        // deal with users' requirements to JSON response formatting and
        // structure, can be conveniently applied to tweak the output.

        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;
    }

    /**
     * Filter JSON encode options array against the whitelist array.
     *
     * @param array $jsonEncodeOptions
     *
     * @return array
     */
    protected function filterJsonEncodeOptions(array $jsonEncodeOptions)
    {
        return array_intersect($jsonEncodeOptions, [JSON_PRETTY_PRINT, JSON_UNESCAPED_UNICODE,]); }}Copy the code