HOW DO I MAP A JSON OBJECT TO A PHP CLASS?

F Scott Fitzgerald

Total Post:29

Points:203
Posted by  F Scott Fitzgerald
JSON 
 2767  View(s)
Ratings:
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.
  1. AVADHESH PATEL

    Post:604

    Points:4228
    Re: How do I map a JSON object to a PHP Class?

    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;
       }
    }

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!