How to map a JSON object to a PHP class?

I am creating a REST API end element that adds a company to a MySQL database. The client sends a POST request with an attached data packet. A data packet is a JSON object. Suppose a JSON company object is formatted to exactly match the company class that uses the API.

How to get JSON company object data in company class? It seems silly to create an instance of the Company object, a json_decode() JSON object, and then call dozens of set() methods.

This seems to be especially stupid, since I plan to offer the same models in my client package for creating objects that are passed as JSON for my API before decoding them and mapping them to the same objects again.

Am I missing something? I constantly come across things that seem redundant when building my API, but maybe this is exactly what should happen.

+7
source share
4 answers

Why don't you handle everything in the constructor of the Company object so that you pass the JSON object as a parameter, and the constructor handles all assignments. This way you don’t even need public methods.

 $companyData = $_POST['company']; //or $companyData = json_decode($_POST['company']); //or whatever depending on how you are posting class Company { private $companyName; //etc... function __construct(array $data) { foreach($data as $key => $val) { if(property_exists(__CLASS__,$key)) { $this->$key = $val; } } } } 
+10
source

We built JsonMapper to automatically map JSON objects on our own model classes.

It is used only for information of type docblock for matching, which in any case has most of the class properties.

+5
source

Why don't you just create a method in the Company object that declares the variables for the object (you do not need to write a set method for each variable, only one that sets all the variables).

 //Why not write something like this in the class function setFromJSON($json){ $jsonArray = json_decode($json, true); foreach($jsonArray as $key=>$value){ $this->$key = $value; } } 
+1
source

Do not map the JSON data you exactly get to the data object you want to use. Changes will be made to the database and objects, and you do not want them to affect the interface you created and vice versa.

+1
source

All Articles