0 追蹤者

類別 yii\web\JsonParser

繼承關係yii\web\JsonParser
實作yii\web\RequestParserInterface
自版本2.0
原始碼 https://github.com/yiisoft/yii2/blob/master/framework/web/JsonParser.php

使用 yii\helpers\Json::decode() 解析原始 HTTP 請求。

若要啟用 JSON 請求的解析,您可以使用此類別配置 yii\web\Request::$parsers

'request' => [
    'parsers' => [
        'application/json' => 'yii\web\JsonParser',
    ]
]

公開屬性

隱藏繼承的屬性

屬性 類型 描述 定義於
$asArray boolean 是否以關聯陣列形式傳回物件。 yii\web\JsonParser
$throwException boolean 若請求主體為無效 JSON 時,是否拋出 yii\web\BadRequestHttpException yii\web\JsonParser

公開方法

隱藏繼承的方法

方法 描述 定義於
parse() 解析 HTTP 請求主體。 yii\web\JsonParser

屬性詳細資訊

隱藏繼承的屬性

$asArray 公開屬性

是否以關聯陣列形式傳回物件。

public boolean $asArray true
$throwException 公開屬性

若請求主體為無效 JSON 時,是否拋出 yii\web\BadRequestHttpException

public boolean $throwException true

方法詳細資訊

隱藏繼承的方法

parse() public method

解析 HTTP 請求主體。

public array|stdClass parse ( $rawBody, $contentType )
$rawBody string

原始 HTTP 請求主體。

$contentType string

請求主體指定的內容類型。

返回 array|stdClass

從請求主體解析的參數

拋出 yii\web\BadRequestHttpException

如果主體包含無效的 JSON 且 $throwExceptiontrue

                public function parse($rawBody, $contentType)
{
    // converts JSONP to JSON
    if (strpos($contentType, 'application/javascript') !== false) {
        $rawBody = preg_filter('/(^[^{]+|[^}]+$)/', '', $rawBody);
    }
    try {
        $parameters = Json::decode($rawBody, $this->asArray);
        return $parameters === null ? [] : $parameters;
    } catch (InvalidArgumentException $e) {
        if ($this->throwException) {
            throw new BadRequestHttpException('Invalid JSON data in request body: ' . $e->getMessage());
        }
        return [];
    }
}