Deserializing from JSON into PHP, with casting?

前端 未结 12 2022
既然无缘
既然无缘 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:46

    Below is an example of using both static (i.e. you know the class type in code) and dynamic (i.e. you only know the class type at runtime) to deserialize JSON back into a PHP object:

    Code

    brand = $brand;
            $this->model = $model;
            $this->year = $year;
        }
    
        public function toJson()
        {
            $arr = array(
                'brand' => $this->brand,
                'model' => $this->model,
                'year' => $this->year,
            );
    
            return json_encode($arr);
        }
    
        public static function fromJson($json)
        {
            $arr = json_decode($json, true);
    
            return new self(
                $arr['brand'],
                $arr['model'],
                $arr['year']
            );
        }
    }
    
    // original object
    echo 'car1: ';
    $car1 = new Car('Hyundai', 'Tucson', 2010);
    var_dump($car1);
    
    // serialize
    echo 'car1class: ';
    $car1class = get_class($car1); // need the class name for the dynamic case below. this would need to be bundled with the JSON to know what kind of class to recreate.
    var_dump($car1class);
    
    echo 'car1json: ';
    $car1Json = $car1->toJson();
    var_dump($car1Json);
    
    // static recreation with direct invocation. can only do this if you know the class name in code.
    echo 'car2: ';
    $car2 = Car::fromJson($car1Json);
    var_dump($car2);
    
    // dynamic recreation with reflection. can do this when you only know the class name at runtime as a string.
    echo 'car3: ';
    $car3 = (new ReflectionMethod($car1class, 'fromJson'))->invoke(null, $car1Json);
    var_dump($car3);
    

    Output

    car1: object(Car)#1 (3) {
      ["brand":"Car":private]=>
      string(7) "Hyundai"
      ["model":"Car":private]=>
      string(6) "Tucson"
      ["year":"Car":private]=>
      int(2010)
    }
    car1class: string(3) "Car"
    car1json: string(48) "{"brand":"Hyundai","model":"Tucson","year":2010}"
    car2: object(Car)#2 (3) {
      ["brand":"Car":private]=>
      string(7) "Hyundai"
      ["model":"Car":private]=>
      string(6) "Tucson"
      ["year":"Car":private]=>
      int(2010)
    }
    car3: object(Car)#4 (3) {
      ["brand":"Car":private]=>
      string(7) "Hyundai"
      ["model":"Car":private]=>
      string(6) "Tucson"
      ["year":"Car":private]=>
      int(2010)
    }
    

提交回复
热议问题