PHP code example of polesphp / json

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

    

polesphp / json example snippets




class Person
{
  /** @var int */
  public $id;
  
  /** @var string */
  public $firstname;

  /** @var string */
  public $lastname

  /** @var Address[] */
  public $addresses;
}

class Address
{
  /** int */
  public $civicNo;

  /** string */
  public $street;

  /** string */
  public $city;

  /** string */
  public $country;

  /** string */
  public $postalCode;
}



use Poles\Json\ClassSerializer;
use Poles\Json\SerializerConfig;

$subject = <<<JSON
{
  "id": 5,
  "firstname": "John",
  "lastname": "Doe",
  "addresses": [
    {
      "civicNo": 1080,
      "street": "Snowboarding Street",
      "city": "Montreal",
      "country": "Canada",
      "postalCode": "H2K1L3"
    }
  ]
}
JSON;

$serializer = new ClassSerializer(Person::class, new SerializerConfig());

// ----- De-serialization -------
$personInstance = $serializer->deserialize($subject);

// ----- Serialization -----
$originalJson = $serializer->serialize($personInstance);



use Poles\Json\ClassSerializer;
use Poles\Json\SerializerConfig;

$config = new SerializerConfig();
$config->setCacheDirectory(sys_get_temp_dir()); // Writeable cache directory for production environments
$config->setMaxDepth(200); // Same as the "max depth" argument of json_encode
$config->setOptions(JSON_PRETTY_PRINT); // Same as the "options" argument of json_encode

$serializer = new ClassSerializer(MyClass::class, $config);