PHP code example of snortlin / json-codec

1. Go to this page and download the library: Download snortlin/json-codec library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

snortlin / json-codec example snippets


use Snortlin\JsonCodec\JsonEncoder;

$json = JsonEncoder::json([
    'name' => 'John',
    'active' => true,
]);

use Snortlin\JsonCodec\JsonEncoder;

$encoder = new JsonEncoder();

$json = $encoder->encode([
    'name' => 'John',
    'active' => true,
]);

use Snortlin\JsonCodec\JsonEncoder;

$json = JsonEncoder::json(
    data: ['name' => 'John'],
    context: [
        JsonEncoder::OPTIONS => JSON_PRETTY_PRINT,
        JsonEncoder::RECURSION_DEPTH => 512,
    ],
);

use Snortlin\JsonCodec\JsonDecoder;

$data = JsonDecoder::array('{"name":"John","active":true}');

use Snortlin\JsonCodec\JsonDecoder;

$object = JsonDecoder::object('{"name":"John","active":true}');

use Snortlin\JsonCodec\JsonDecoder;

$decoder = new JsonDecoder();

$data = $decoder->decode('{"name":"John","active":true}');

use Snortlin\JsonCodec\JsonDecoder;

$data = JsonDecoder::array(
    data: '{"name":"John"}',
    context: [
        JsonDecoder::RECURSION_DEPTH => 512,
    ],
);

use Snortlin\JsonCodec\JsonDecoder;

$data = (new JsonDecoder())->decode(
    data: '{"name":"John"}',
    context: [
        JsonDecoder::ASSOCIATIVE => true,
        JsonDecoder::RECURSION_DEPTH => 512,
    ],
);

use Snortlin\JsonCodec\JsonEncoder;
use Snortlin\JsonCodec\Encoder\JsonEncoderAdapterInterface;

final class CustomEncoderAdapter implements JsonEncoderAdapterInterface
{
    public function encode(mixed $value, int $flags, int $depth): string
    {
        // Custom implementation
    }
}

$encoder = new JsonEncoder(
    encoder: new CustomEncoderAdapter(),
);

use Snortlin\JsonCodec\JsonDecoder;
use Snortlin\JsonCodec\Decoder\JsonDecoderAdapterInterface;

final class CustomDecoderAdapter implements JsonDecoderAdapterInterface
{
    public function decode(string $json, bool $associative, int $depth): mixed
    {
        // Custom implementation
    }
}

$decoder = new JsonDecoder(
    decoder: new CustomDecoderAdapter(),
);