PHP与Android Kotlin交互JSON解析异常求助:String无法转JSONArray
Hey there! Let's fix this JSON parsing error step by step.
The Root Cause (It's in Your PHP Script!)
Your problem comes down to invalid output from the PHP side. Look at the browser output you shared: it starts with Array (...) instead of pure JSON. That's because after you echo $json; (which outputs the correct JSON), you added print_r($data); — this dumps the raw array text right after the JSON, making the entire response a messy mix of valid JSON and plain text. No JSON parser can handle that, which explains both the Android JSONException and browser SyntaxError.
Fix the PHP Script
Simply remove the print_r($data); line. This line is only for debugging and ruins the pure JSON format your app needs. Here's the cleaned-up code:
<?php require_once 'connect.php'; $sql="SELECT * FROM events ORDER BY Eid DESC"; $result=$conn->query($sql); $data = array(); if($result->num_rows >0){ while($row = $result->fetch_assoc()){ $data[] = array( 'Title' => $row["Title"], 'Date' => $row["Date"], 'Time' => $row["Time"], 'Location' => $row["Location"], 'image_url' => $row["image_url"] ); } } header('Content-Type:application/json'); $json = json_encode($data, JSON_UNESCAPED_UNICODE); echo $json; // Remove this line: print_r($data); exit; ?>
Quick Fix for Your Android Kotlin Code
While we're at it, there's a small bug in your parsing logic: you're trying to get Date and Time as integers with obj.getInt(), but those values are strings (like 2018-01-31 and 04:30:00). This will throw another JSONException once the PHP issue is fixed. Update those lines to use getString() instead:
// Replace these lines: // events.setDate(obj.getInt("Date")) // events.setTime(obj.getInt("Time")) // With: events.setDate(obj.getString("Date")) events.setTime(obj.getString("Time"))
Verify the Fix
After updating the PHP script, visit the URL in your browser — you should see only a clean JSON array like this:
[{"Title":"Pediatrics 1st Bekaa","Date":"2018-01-31","Time":"04:30:00","Location":"Bekaa","image_url":"http://www.khazaal.tech/DoctorMobileApp/images/2.PNG"},...]
Once that's working, your Android app's JsonArrayRequest will parse the response correctly, and the list will populate as expected.
内容的提问来源于stack exchange,提问作者Sandra Khazaal




