<?php
abstract class JsonDeserializer
{
/**
* @param string|array $json
* @return $this
*/
public static function Deserialize($json)
{
$className = get_called_class();
$classInstance = new $className();
foreach ($json as $key => $value)
$classInstance->{$key} = $value;
return $classInstance;
}
/**
* @param string $json
* @return $this[]
*/
public static function DeserializeArray($json)
{
$items = [];
foreach ($json as $item)
$items[] = self::Deserialize($item);
return $items;
}
}
class MyObject extends JsonDeserializer
{
/** @var string */
public $property1;
/** @var string */
public $property2;
/** @var string */
public $property3;
/** @var string */
public $array1;
}
$objectInstance = new MyObject();
$objectInstance->property1 = 'Value 1';
$objectInstance->property2 = 'Value 2';
$objectInstance->property3 = 'Value 3';
$objectInstance->array1 = ['Key 1' => 'Value 1', 'Key 2' => 'Value 2'];
$deserializedInstance = MyObject::Deserialize($jsonSerialized);
PD9waHAKCmFic3RyYWN0IGNsYXNzIEpzb25EZXNlcmlhbGl6ZXIKewogICAgLyoqCiAgICAgKiBAcGFyYW0gc3RyaW5nfGFycmF5ICRqc29uCiAgICAgKiBAcmV0dXJuICR0aGlzCiAgICAgKi8KICAgIHB1YmxpYyBzdGF0aWMgZnVuY3Rpb24gRGVzZXJpYWxpemUoJGpzb24pCiAgICB7CiAgICAgICAgJGNsYXNzTmFtZSA9IGdldF9jYWxsZWRfY2xhc3MoKTsKICAgICAgICAkY2xhc3NJbnN0YW5jZSA9IG5ldyAkY2xhc3NOYW1lKCk7CiAgICAgICAgaWYgKGlzX3N0cmluZygkanNvbikpCiAgICAgICAgICAgICRqc29uID0ganNvbl9kZWNvZGUoJGpzb24pOwogICAgICAgIGZvcmVhY2ggKCRqc29uIGFzICRrZXkgPT4gJHZhbHVlKQogICAgICAgICAgICAkY2xhc3NJbnN0YW5jZS0+eyRrZXl9ID0gJHZhbHVlOwogICAgICAgIHJldHVybiAkY2xhc3NJbnN0YW5jZTsKICAgIH0KICAgIC8qKgogICAgICogQHBhcmFtIHN0cmluZyAkanNvbgogICAgICogQHJldHVybiAkdGhpc1tdCiAgICAgKi8KICAgIH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