Deserializing from JSON into PHP, with casting?

前端 未结 12 2028
既然无缘
既然无缘 2021-01-31 04:38

Suppose I have a User class with \'name\' and \'password\' properties, and a \'save\' method. When serializing an object of this class to JSON via json_encode, the method is pro

12条回答
  •  野的像风
    2021-01-31 04:58

    Old question, but maybe someone will find this useful.
    I've created an abstract class with static functions that you can inherit on your object in order to deserialize any JSON into the inheriting class instance.

    abstract class JsonDeserializer
    {
        /**
         * @param string|array $json
         * @return $this
         */
        public static function Deserialize($json)
        {
            $className = get_called_class();
            $classInstance = new $className();
            if (is_string($json))
                $json = json_decode($json);
    
            foreach ($json as $key => $value) {
                if (!property_exists($classInstance, $key)) continue;
    
                $classInstance->{$key} = $value;
            }
    
            return $classInstance;
        }
        /**
         * @param string $json
         * @return $this[]
         */
        public static function DeserializeArray($json)
        {
            $json = json_decode($json);
            $items = [];
            foreach ($json as $item)
                $items[] = self::Deserialize($item);
            return $items;
        }
    }
    

    You use it by inheriting it on a class which has the values that your JSON will have:

    class MyObject extends JsonDeserializer
    {
        /** @var string */
        public $property1;
    
        /** @var string */
        public $property2;
    
        /** @var string */
        public $property3;
    
        /** @var array */
        public $array1;
    }
    

    Example usage:

    $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'];
    
    $jsonSerialized = json_encode($objectInstance);
    
    $deserializedInstance = MyObject::Deserialize($jsonSerialized);
    

    You can use the ::DeserializeArray method if your JSON contains an array of your target object.

    Here's a runnable sample.

提交回复
热议问题