Webmozart\Json\JsonDecoder::decode PHP Method

decode() public method

If a schema is passed, the decoded object is validated against that schema. The schema may be passed as file path or as object returned from JsonDecoder::decodeFile($schemaFile). You can adjust the decoding with {@link setObjectDecoding()}, {@link setBigIntDecoding()} and {@link setMaxDepth()}. Schema validation is not supported when objects are decoded as associative arrays.
public decode ( string $json, string | object $schema = null ) : mixed
$json string The JSON string
$schema string | object The schema file or object
return mixed The decoded value
    public function decode($json, $schema = null)
    {
        if (self::ASSOC_ARRAY === $this->objectDecoding && null !== $schema) {
            throw new \InvalidArgumentException('Schema validation is not supported when objects are decoded ' . 'as associative arrays. Call ' . 'JsonDecoder::setObjectDecoding(JsonDecoder::JSON_OBJECT) to fix.');
        }
        $decoded = $this->decodeJson($json);
        if (null !== $schema) {
            $errors = $this->validator->validate($decoded, $schema);
            if (count($errors) > 0) {
                throw ValidationFailedException::fromErrors($errors);
            }
        }
        return $decoded;
    }

Usage Example

 /**
  * POST request handling
  * 
  * @param string $path
  * @param array $data
  *
  * @return GuzzleHttp\RequestInterface
  */
 public function post($path, $data = array())
 {
     $response = $this->httpClient->request('POST', $path, ['json' => $data]);
     if ($response->getStatusCode() !== 200) {
         throw new \UnexpectedValueException('HTTP Status: ' . $response->getStatusCode());
     }
     return $this->decoder->decode($response->getBody());
 }
All Usage Examples Of Webmozart\Json\JsonDecoder::decode