---
title: "How do I map a JSON object to a PHP Class?"  
description: "How do I map a JSON object to a PHP Class?"  
author: "Anonymous User"  
published: 2013-06-20  
updated: 2013-06-20  
canonical: https://www.mindstick.com/forum/1247/how-do-i-map-a-json-object-to-a-php-class  
category: "json"  
tags: ["json"]  
reading_time: 2 minutes  

---

# How do I map a JSON object to a PHP Class?

Hi [Developers](https://www.mindstick.com/articles/12875/blunders-you-must-avoid-while-hiring-java-developers-to-get-the-best-fulfilling-your-needs),\
\
I'm [building](https://www.mindstick.com/blog/23088/which-tonewood-is-suitable-for-building-a-guitar) a [REST API](https://www.mindstick.com/forum/160553/how-to-authenticate-rest-api-in-c-sharp) endpint that adds a company to a [MySQL database](https://answers.mindstick.com/qa/38302/what-is-the-main-difference-between-innodb-myisam-mysql-database-engines). The client sends a POST [request](https://www.mindstick.com/blog/255/post-get-and-request-function-in-php) with an attached data package. The data package is a [JSON object](https://www.mindstick.com/forum/699/how-to-parse-into-json-object-using-json-parse-in-node-js). 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](https://answers.mindstick.com/qa/32060/who-is-the-chairman-of-planning-commissison) on [offering](https://answers.mindstick.com/qa/116481/a-complete-look-at-umrah-packages-offering-5-star-comfort) the same models in my client package to build the [objects](https://www.mindstick.com/forum/145447/what-are-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](https://yourviews.mindstick.com/view/81332/the-approach-of-science-against-disease-epidemics) things that seem redundant while building my API, but perhaps that's just what has to happen.\

## Replies

### Reply by AVADHESH PATEL

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;** **}****}**


---

Original Source: https://www.mindstick.com/forum/1247/how-do-i-map-a-json-object-to-a-php-class

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
