PHP code example of jesseschalken / pure-json

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

    

jesseschalken / pure-json example snippets


use PureJSON\JSON;

$json  = JSON::encode($value);
$value = JSON::decode($json);

use PureJson\JSON;

$company = array(
    'name'      => 'Good Company',
    'employees' => array(
    	array(
        	'name' => 'Jesse',
            'role' => 'sales',
        ),
        array(
        	'name' => 'Ben',
            'role' => 'development',
        ),
    ),
);

// encode/decode will reproduce the original array
$json    = JSON::encode($company);
$company = JSON::decode($json);

use PureJson\JSON;
use PureJson\Serializable;

class Company implements Serializable {
    public static function jsonCreate(array $props) {
        return new self($props['name'], $props['employees']);
    }

    public static function jsonType() {
    	return 'company';
    }

    private $name;
    private $employees;

    public function __construct($name, $employees) {
    	$this->name      = $name;
        $this->employees = $employees;
    }

    public function jsonProps() {
        return array(
            'name'      => $this->name,
            'employees' => $this->employees,
        );
    }
}

class Employee implements Serializable {
    public static function jsonCreate(array $props) {
        return new self($props['name'], $props['role']);
    }

    public static function jsonType() {
        return 'employee';
    }

    private $name;
    private $role;

    public function __construct($name, $role) {
        $this->name = $name;
        $this->role = $role;
    }

    public function jsonProps() {
        return array(
            'name' => $this->name,
            'role' => $this->role,
        );
    }
}

$company = new Company(
    'Good Company',
    array(
    	new Employee('Jesse', 'sales'),
        new Employee('Ben', 'development'),
    )
);

// serialize/deserialize will produce the original object graph
$json    = JSON::serialize($company);
$company = JSON::deserialize($json, array(
    Company::class,
    Employee::class,
));