PHP code example of niko9911 / json-to-entity

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

    

niko9911 / json-to-entity example snippets



declare(strict_types=1);

// Declare entity where to map.
final class Basic
{
    /**
     * @var string
     */
    private $bar;
    /**
     * @var int|null
     */
    private $foo;
    /**
     * @var array
     */
    private $fooBar;

    /**
     * BasicUnitTestEntity constructor.
     *
     * @param string $bar
     * @param int    $foo
     * @param array  $fooBar
     */
    public function __construct(string $bar, ?int $foo, array $fooBar)
    {
        $this->bar = $bar;
        $this->foo = $foo;
        $this->fooBar = $fooBar;
    }

    /**
     * @return string
     */
    public function getBar(): string
    {
        return $this->bar;
    }

    /**
     * @return int|null
     */
    public function getFoo(): ?int
    {
        return $this->foo;
    }

    /**
     * @return array
     */
    public function getFooBar(): array
    {
        return $this->fooBar;
    }
}

// JSON
$json = <<<JSON
{
  "bar": "Some_Bar",
  "foo": 10,
  "fooBar": ["a", "b", "c"]
}
JSON;

$mapper = new \Niko9911\JsonToEntity\Mapper();
$entity = $mapper->map(\json_decode($json), Basic::class);
var_dump($entity);
//class Basic#25 (3) {
//  private $bar =>
//  string(8) "Some_Bar"
//  private $foo =>
//  int(10)
//  private $fooBar =>
//  array(3) {
//    [0] =>
//    string(1) "a"
//    [1] =>
//    string(1) "b"
//    [2] =>
//    string(1) "c"
//  }
//}