Home > DeveloperSection > Forums > How do I map a JSON object to a PHP Class?
F Scott Fitzgerald
F Scott Fitzgerald

Total Post:29

Points:203
Posted on    June-20-2013 3:27 AM

 JSON JSON 
Ratings:


 1 Reply(s)
 2193  View(s)
Rate this:
Hi Developers,

I'm building a REST API endpint that adds a company to a MySQL database. The client sends a POST request with an attached data package. The data package is a JSON object. Assume the JSON Company Object is formatted to exactly match the Company Class that the API uses.

How do I get the JSON Company Object data into the Company Class? It seems silly to instantiate a Company Object, json_decode() the JSON Object, then call dozens of set() methods.

It seems especially silly, since I'm planning on offering the same models in my client package to build the objects that get passed as JSON to my API, before being decoded, and mapped back into the same objects again.

Am I missing something? I'm constantly running up against things that seem redundant while building my API, but perhaps that's just what has to happen.


AVADHESH PATEL

Total Post:604

Points:4228
Posted on    June-20-2013 7:46 AM

Hi,

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

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

Don't want to miss updates? Please click the below button!

Follow MindStick