PHP code example of andrewsauder / json-deserialize
1. Go to this page and download the library: Download andrewsauder/json-deserialize 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/ */
andrewsauder / json-deserialize example snippets
protected static function _beforeJsonDeserialize( string|\stdClass $json ): void {}
protected function _afterJsonDeserialize() : void {}
protected function _beforeJsonSerialize() : void {}
class myModel extends \andrewsauder\jsonDeserialize\jsonDeserialize {
public int $varA = 1;
public string $varB = 'B1';
#[excludeJsonDeserialize]
public string $varC = 'C1';
/** @var string[] */
public array $varD = [ 'D1', 'D2', 'D3' ];
public int $varASquared = 1;
protected function _afterJsonDeserialize() {
//automagically called after self::jsonDeserialize() has finished its deserialization
$this->varASquared = $this->varA * $this->varA;
}
protected function _beforeJsonSerialize() {
//automagically called before json_encode( {$this} ) serializes object into JSON
$this->varASquared = $this->varA * $this->varA;
}
}
class myController {
public function post() {
$jsonString = '{ "varA":2, "varASquared":3, "varB":"B2", "varC":"C2", "varD":[ "D4", "D5", "D6" ] }';
$myModel = myModel::jsonDeserialize( $jsonString );
//$myModel is now an instance of myModel
echo $myModel->varA;
echo $myModel->varASquared; //<-Note that this property is updated in _afterJsonDeserialize
echo $myModel->varB;
echo $myModel->varC; //<-This property's value is not set from the JSON because it has #[excludeJsonDeserialize]
foreach( $myModel->varD as $i=>$v) {
echo $myModel->varD[ $i ];
}
}
}