類別 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 |
屬性詳細資訊
若請求主體為無效 JSON 時,是否拋出 yii\web\BadRequestHttpException
方法詳細資訊
解析 HTTP 請求主體。
public array|stdClass parse ( $rawBody, $contentType ) | ||
$rawBody | string |
原始 HTTP 請求主體。 |
$contentType | string |
請求主體指定的內容類型。 |
返回 | array|stdClass |
從請求主體解析的參數 |
---|---|---|
拋出 | yii\web\BadRequestHttpException |
如果主體包含無效的 JSON 且 $throwException 為 |
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 [];
}
}
註冊 或 登入 以便評論。