skip to Main Content

I have a JSON:

{
   "id":1,
   "name":"John",
   "firstname":"Doe"
}

Server side, I do it:

$input = $request->json()->all();
$user = new User();
$user->id = $input['id'];
$user->name = $input['name'];
$user->firstname = $input['firstname'];

Does it possible to auto fill my object with a JSON, if the the JSON fields and my object fields are the same ? Like below ?

$user = new User();
$user->fromJSON($input);

2

Answers


  1. Yes, it’s possible to create a method fromJSON() in your User class to automatically fill the object properties from a JSON input. Here’s how you can do it:

    class User {
        public $id;
        public $name;
        public $firstname;
    
        public function fromJSON($json) {
            $data = json_decode($json, true);
    
            foreach ($data as $key => $value) {
                if (property_exists($this, $key)) {
                    $this->{$key} = $value;
                }
            }
        }
    }
    
    // Example usage:
    $input = '{
       "id":1,
       "name":"John",
       "firstname":"Doe"
    }';
    
    $user = new User();
    $user->fromJSON($input);
    
    // Now $user has its properties filled with values from the JSON
    echo $user->id; // Outputs: 1
    echo $user->name; // Outputs: John
    echo $user->firstname; // Outputs: Doe
    

    This method fromJSON() takes a JSON string as input, decodes it into an associative array, and then iterates over each key-value pair. If a property with the same name exists in the User class, it assigns the corresponding value from the JSON data to that property.

    Login or Signup to reply.
  2. You can use the json_decode function to convert a JSON string into a PHP object.

    I have updated your code like below:

    $jsonString = '{"id":1,"name":"John","firstname":"Doe"}';
    
    $userObject = json_decode($jsonString);
    
    // If you need to convert it to an associative array, you can pass true as the second parameter
    $userArray = json_decode($jsonString, true);
    

    If you have a class User and you want to fill its properties with values from a JSON string, you could write a method in the User class that takes a JSON string, decodes it, and sets the properties accordingly:

    class User {
      public $id;
      public $name;
      public $firstname;
    
      public function fromJSON($jsonString) {
        $jsonObject = json_decode($jsonString);
        $this->id = $jsonObject->id;
        $this->name = $jsonObject->name;
        $this->firstname = $jsonObject->firstname;
      }
    }
    
    // Usage
    $user = new User();
    $user->fromJSON($jsonString);
    

    This simple example does not include error checking or more complex scenarios such as nested objects or arrays.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search