codekandis/json-codec

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()`.

3.0.0 2024-05-16 23:00 UTC

This package is auto-updated.

Last update: 2024-05-16 23:01:18 UTC


README

Version License Minimum PHP Version Code Coverage

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().

Index

Installation

Install the latest version with

$ composer require codekandis/json-codec

How to use

Encoding values

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 );

Decoding values

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 );

Differences to PHP's JSON functions

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.