How to Return JSON Object from PHP to Read from Android App
Building a bridge between a PHP backend and an Android client requires more than just dumping raw database rows into a string. The core challenge lies in structuring the data so that both sides agree on how it is serialized and deserialized. When querying a MySQL table like the one shown below, the goal is to fetch matching records based on inputâsuch as a dealer nameâand send them back in a format the Android app can parse reliably using org.json.
To achieve this, you must construct a PHP response that wraps your data in a predictable structure. In the example provided, the PHP script iterates through query results and builds a nested array before encoding it. The logic involves initializing an empty associative array for the main payload, pushing individual row objects into a specific key (e.g., "stuff"), and adding a status flag like "success": 1 to indicate completion.
<?php
// Assuming $conn is established
$result = $conn->query("SELECT pname FROM products");
$response["stuff"] = array();
while($row = $result->fetch_assoc()) {
$stuff = array();
/* ADD THE TABLE COLUMNS TO THE JSON OBJECT CONTENTS */
$stuff["pname"] = $row['pname'];
array_push($response["stuff"], $stuff);
}
// Add success flag
$response["success"] = 1;
echo(json_encode($response));
mysqli_close($conn);
?>
This approach generates a JSON object where the data resides inside an array key. The output looks like this:
{"stuff":[{"pname":"Advocates"},{"pname":"Notaries"}],"success":1}
On the Android side, parsing this structure is straightforward but requires strict adherence to the keys defined in PHP. Using the org.json library, you first retrieve the root JSONObject. You must check the integer value of the "success" key before attempting to access the data array. If the success flag is missing or set to 0, accessing the "stuff" array will throw an exception because that path doesn't exist in the response object.
Once validated, you extract the JSONArray associated with the "stuff" key. Iterating through this array allows you to parse each item as a JSONObject. A common pitfall is ignoring the root structure and trying to read directly from a non-existent top-level array. By strictly following the hierarchyâRoot Object -> Success Check -> Stuff Array -> Individual Itemâyou ensure robustness even if the database returns an empty set or the server fails silently.
Best Practices for JSON Responses
While the manual method using json_encode works well for simple scripts, relying on it can lead to inconsistent data structures if the logic changes. A more maintainable approach is to utilize a dedicated response model class in PHP. This encapsulates the array structure and ensures that every request returns a standardized object with keys like success, message, and data.
For larger projects or those seeking better type safety and built-in validation, switching to Laravel is a significant upgrade. Laravel provides robust helpers for returning JSON responses automatically. You can use the json() helper method or the response()->json() facade to return data with appropriate HTTP status codes (like 200 OK) without manually echoing strings. This reduces the risk of forgetting to close database connections or accidentally exposing sensitive error messages in the response body.
If you are maintaining a legacy PHP application, sticking to the associative array pattern shown above is perfectly valid, provided you always validate the structure before parsing on the client side. The key takeaway is consistency: define your JSON contract clearly and enforce it on both the server and the client.