Class yii\web\JsonParser
| Inheritance | yii\ |
|---|---|
| Implements | yii\ |
| Available since version | 2.0 |
| Source Code | https://github.com/yiisoft/yii2/blob/master/framework/web/JsonParser.php |
Parses a raw HTTP request using yii\
To enable parsing for JSON requests you can configure yii\
'request' => [
'parsers' => [
'application/json' => 'yii\web\JsonParser' ,
]
]
Public Properties
| Property | Type | Description | Defined By |
|---|---|---|---|
| $asArray | boolean | Whether to return objects in terms of associative arrays. | yii\ |
| $throwException | boolean | Whether to throw a yii\ |
yii\ |
Public Methods
| Method | Description | Defined By |
|---|---|---|
| parse() | Parses a HTTP request body. | yii\ |
Property Details
Whether to return objects in terms of associative arrays.
Whether to throw a yii\
Method Details
Parses a HTTP request body.
| public mixed parse ( string $rawBody, string $contentType ) | ||
| $rawBody | string |
The raw HTTP request body. |
| $contentType | string |
The content type specified for the request body. |
| return | mixed |
Parameters parsed from the request body |
|---|---|---|
| throws | yii\ |
if the body contains invalid json and $throwException is |
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 [];
}
}
User Contributed Notes
Leave a comment
Join the conversation to share a note.