Deserializing from JSON into PHP, with casting?

前端 未结 12 2025
既然无缘
既然无缘 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 05:09

    Old question, new answer.

    What about creating your own interface to match JsonSerializable? ;)

    /**
     * Interface JsonUnseriablizable
     */
    interface JsonUnseriablizable {
        /**
         * @param array $json
         */
        public function jsonUnserialize(array $json);
    }
    

    example:

    /**
     * Class Person
     */
    class Person implements JsonUnseriablizable {
    
        public $name;
        public $dateOfBirth;
    
        /**
         * @param string $json
         */
        public function jsonUnserialize(array $json)
        {
            $this->name = $json['name'] ?? $this->name;
            $this->dateOfBirth = $json['date_of_birth'] ?? $this->dateOfBirth;
        }
    }
    
    $json = '{"name":"Bob","date_of_birth":"1970-01-01"}';
    
    $person = new Person();
    if($person instanceof JsonUnseriablizable){
        $person->jsonUnserialize(json_decode($json, true, 512, JSON_THROW_ON_ERROR));
    }
    
    var_dump($person->name);
    

提交回复
热议问题