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);
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.