PHP code example of karriere / json-decoder

1. Go to this page and download the library: Download karriere/json-decoder 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/ */

    

karriere / json-decoder example snippets


#[AllowDynamicProperties]
class Person
{
    public int $id;
    public string $name;
    public ?string $lastname = '';
}

$jsonDecoder = new JsonDecoder();
$jsonData = '{"id": 1, "name": "John Doe", "lastname": null, "dynamicProperty": "foo"}';

$person = $jsonDecoder->decode($jsonData, Person::class);

class Person
{
    public int $id;
    public string $name;

    /**
     * @var Address
     */
    public $address;
    
    public ?Address $typedAddress = null;
}

$jsonDecoder = new JsonDecoder();
$jsonDecoder->scanAndRegister(Person::class);

$jsonData = '{"id": 1, "name": "John Doe", "address": {"street": "Samplestreet", "city": "Samplecity"}, , "typedAddress": {"street": "Samplestreet", "city": "Samplecity"}}';

$person = $jsonDecoder->decode($jsonData, Person::class);

class Person
{
    public int $id;
    public string $name;
    public mixed $address;
}

class PersonTransformer implements Transformer
{
    public function register(ClassBindings $classBindings)
    {
        $classBindings->register(new FieldBinding('address', 'address', Address::class));
    }

    public function transforms()
    {
        return Person::class;
    }
}

$jsonDecoder = new JsonDecoder();
$jsonDecoder->register(new PersonTransformer());

$jsonData = '{"id": 1, "name": "John Doe"}';

$person = $jsonDecoder->decode($jsonData, Person::class);

$jsonDecoder = new JsonDecoder();

$jsonData = '[{"id": 1, "name": "John Doe"}, {"id": 2, "name": "Jane Doe"}]';

$personArray = $jsonDecoder->decodeMultiple($jsonData, Person::class);

new FieldBinding(string $property, ?string $jsonField = null, ?string $type = null, bool $isRequired = false);

new ArrayBinding(string $property, ?string $jsonField = null, ?string $type = null, bool $isRequired = false);

new AliasBinding(string $property, ?string $jsonField = null, bool $isRequired = false);

new DateTimeBinding(string $property, ?string $jsonField = null, bool $isRequired = false, $dateTimeFormat = DateTime::ATOM);

new CallbackBinding(string $property, private Closure $callback);