Android无法解析PHP返回的JSON坐标添加地图标记问题排查
问题分析与解决方案
你已经精准定位到了问题的核心:Java代码中尝试用getJSONArray("locatie")解析,但PHP接口返回的locatie是一个带数字索引的JSON对象,而非标准的JSON数组,这直接导致解析失败,无法执行后续的添加地图标记逻辑。
下面给出两种针对性的解决办法,优先推荐第一种(更符合JSON语义规范):
方案1:修改PHP接口,返回标准JSON数组
你的PHP代码中,$response['locatie'][$i] = $locatie;这一行用自增数字作为键名,最终生成的是JSON对象而非数组。我们只需要把locatie初始化为空数组,直接向其中追加元素即可:
$problema = $_POST['problema']; $stmt = $conn->prepare("SELECT latitudine, longitudine, tip_problema FROM alerte WHERE tip_problema = ?"); $stmt->bind_param("s", $problema); $stmt->execute(); $stmt->store_result(); // 先初始化locatie为标准空数组 $response['locatie'] = []; if($stmt->num_rows > 0){ $stmt->bind_result($latitudine, $longitudine, $tip_problema); while($stmt->fetch()) { $locatie = array( 'latitudine'=>$latitudine, 'longitudine'=>$longitudine, 'tip_problema'=>$tip_problema ); $response['error'] = false; $response['message'] = 'Alerta raportata'; // 直接向数组追加元素,无需手动指定数字键 $response['locatie'][] = $locatie; } }else{ $response['error'] = true; $response['message'] = 'Eroare de identificare a alertelor'; } // 记得输出JSON格式的响应 echo json_encode($response);
修改后返回的JSON中,locatie会变成标准数组格式:
{ "error": false, "message": "Alerta raportata", "locatie": [ { "latitudine": 37.4254, "longitudine": -122.08, "tip_problema": "Semafor nefunctional" }, { "latitudine": 37.4259, "longitudine": -122.088, "tip_problema": "Semafor nefunctional" } ] }
此时你原有的Java代码就能正常解析locatie数组,顺利执行addMarker逻辑了。
方案2:不修改PHP,调整Java代码解析JSON对象
如果因特殊原因无法修改PHP接口,可以调整Java代码,将locatie当作JSON对象来解析,遍历它的所有键值对:
@Override protected void onPostExecute(String s) { super.onPostExecute(s); try { JSONObject obj = new JSONObject(s); if (!obj.getBoolean("error")) { Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show(); // 将locatie视为JSONObject而非JSONArray JSONObject locatieObj = obj.getJSONObject("locatie"); // 获取对象所有键的迭代器 Iterator<String> keys = locatieObj.keys(); while (keys.hasNext()) { String key = keys.next(); JSONObject locatie = locatieObj.getJSONObject(key); if(!locatie.isNull("latitudine") && !locatie.isNull("longitudine")) { // 优化:直接用getDouble获取数值,避免字符串转Double的额外操作 latitudine_sql = locatie.getDouble("latitudine"); longitudine_sql = locatie.getDouble("longitudine"); addMarker(latitudine_sql, longitudine_sql); } tip_problema_sql = locatie.getString("tip_problema"); } } else { Toast.makeText(getApplicationContext(), "Some error occurred", Toast.LENGTH_SHORT).show(); } } catch (JSONException e) { e.printStackTrace(); // 调试提示:添加Toast方便快速定位解析问题 Toast.makeText(getApplicationContext(), "JSON解析失败: " + e.getMessage(), Toast.LENGTH_SHORT).show(); } }
额外调试小技巧:可以在Java代码中添加Log.d("JSON Response", s),把接口返回的原始JSON字符串打印到日志中,能帮你快速排查解析类问题。
内容的提问来源于stack exchange,提问作者Costin
相关产品推荐
相关产品推荐

