4 * This file is part of the Symfony package.
6 * (c) Fabien Potencier <fabien@symfony.com>
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Symfony\Component\Serializer\Encoder;
14 use Symfony\Component\Serializer\Exception\UnexpectedValueException;
19 * @author Sander Coolen <sander@jibber.nl>
21 class JsonDecode implements DecoderInterface
24 * Specifies if the returned result should be an associative array or a nested stdClass object hierarchy.
31 * Specifies the recursion depth.
35 private $recursionDepth;
37 private $lastError = JSON_ERROR_NONE;
39 protected $serializer;
42 * Constructs a new JsonDecode instance.
44 * @param bool $associative True to return the result associative array, false for a nested stdClass hierarchy
45 * @param int $depth Specifies the recursion depth
47 public function __construct($associative = false, $depth = 512)
49 $this->associative = $associative;
50 $this->recursionDepth = (int) $depth;
56 * @param string $data The encoded JSON string to decode
57 * @param string $format Must be set to JsonEncoder::FORMAT
58 * @param array $context An optional set of options for the JSON decoder; see below
60 * The $context array is a simple key=>value array, with the following supported keys:
62 * json_decode_associative: boolean
63 * If true, returns the object as associative array.
64 * If false, returns the object as nested stdClass
65 * If not specified, this method will use the default set in JsonDecode::__construct
67 * json_decode_recursion_depth: integer
68 * Specifies the maximum recursion depth
69 * If not specified, this method will use the default set in JsonDecode::__construct
71 * json_decode_options: integer
72 * Specifies additional options as per documentation for json_decode. Only supported with PHP 5.4.0 and higher
76 * @throws UnexpectedValueException
78 * @see http://php.net/json_decode json_decode
80 public function decode($data, $format, array $context = array())
82 $context = $this->resolveContext($context);
84 $associative = $context['json_decode_associative'];
85 $recursionDepth = $context['json_decode_recursion_depth'];
86 $options = $context['json_decode_options'];
88 $decodedData = json_decode($data, $associative, $recursionDepth, $options);
90 if (JSON_ERROR_NONE !== $this->lastError = json_last_error()) {
91 throw new UnexpectedValueException(json_last_error_msg());
100 public function supportsDecoding($format)
102 return JsonEncoder::FORMAT === $format;
106 * Merges the default options of the Json Decoder with the passed context.
108 * @param array $context
112 private function resolveContext(array $context)
114 $defaultOptions = array(
115 'json_decode_associative' => $this->associative,
116 'json_decode_recursion_depth' => $this->recursionDepth,
117 'json_decode_options' => 0,
120 return array_merge($defaultOptions, $context);