With the JSON codec you will be able to encode into and decode from JSON data in an object oriented way. It wraps PHP's functions json_encode()
and json_decode()
.
Install the latest version with
$ composer require codekandis/json-codec
The following example shows how to encode a value.
$value = [
'foo',
'bar'
];
( new JsonEncoder() )
->encode( $value );
$options = new JsonEncoderOptions( JsonEncoderOptions::FORCE_OBJECT | JsonEncoderOptions::PRETTY_PRINT );
( new JsonEncoder() )
->encode( $value, $options );
The following examples show how to decode a value.
$value = '{"0":"foo","1":"bar"}';
( new JsonDecoder() )
->decode( $value );
$options = new JsonDecoderOptions( JsonDecoderOptions::OBJECT_AS_ARRAY );
( new JsonDecoder() )
->decode( $value, $options );
$options = new JsonDecoderOptions( JsonDecoderOptions::OBJECT_AS_ARRAY );
$recursionDepth = 2;
( new JsonDecoder() )
->decode( $value, $options, $recursionDepth );
json_decode()
accepts an additional argument $assoc
to specify if the value forced to be decoded into an associative array. This argument is omitted in the JsonDecoder
while this behaviour can be set explicitly with the JsonDecoderOptions::OBJECT_TO_ARRAY
.