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
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: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.You can use the json_decode function to convert a JSON string into a PHP object.
I have updated your code like below:
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:
This simple example does not include error checking or more complex scenarios such as nested objects or arrays.