在我的应用程序中,logcat Android返回"响应无法解析为JSON数据"当我想通过php文件从Mysqli数据库获取数据时,我无法获取数据"消息"。
PHP文件:
<?php
/*
* Following code will get all cars
* A alert is identified by id
*/
ini_set('error_reporting', E_ALL);
ini_set('display_errors', '1');
// array for JSON response
$response = array();
// include db connect class
require_once('/***/db_config/db_connect.php');
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["id"])) {
$id = $_GET['id'];
// get list of car from Vehicule table
$result = mysqli_query($db->connect(),
"SELECT Alerte.id, Alerte.DateCreation ,SousAlerte, Recepteur, Utilisateur.pseudo as lanceur, Message.Message, Alerte.Lanceur as idLanceur FROM Alerte, Message,Utilisateur WHERE Recepteur= $id and Alerte.Message = Message.id and Alerte.Lanceur=Utilisateur.id");
if (!empty($result)) {
// check for empty result
if (mysqli_num_rows($result) > 0) {
// user node
$response["alerts"] = array();
while ($row = mysqli_fetch_array($result)) {
$alerts = array();
$alerts["id"] = $row["id"];
$alerts["SousAlerte"] = $row['SousAlerte'];
$alerts["Message"] = $row["Message"];
$alerts["idLanceur"] = $row['idLanceur'];
$alerts["Lanceur"] = $row['lanceur'];
$alerts["Recepteur"] = $row['Recepteur'];
$alerts["DateCreation"] = $row['DateCreation'];
array_push($response["alerts"], $alerts);
}
// success
$response["success"] = 1;
// echoing JSON response
echo json_encode($response);
} else {
// no alert found
$response["success"] = 0;
$response["message"] = "No alert found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no alert found
$response["success"] = 0;
$response["message"] = "No alert found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
我获得了JAVA方法的数据:
public List<AlertData> getAllAlerts() {
return allAlerts;
}
public void setAllAlerts(JSONObject jsonObject) {
try {
JSONArray alerts = jsonObject.getJSONArray("alerts");
for (int i = 0; i < alerts.length(); i++) {
JSONObject row = alerts.getJSONObject(i);
String id = row.getString("id");
String message = row.getString("Message");
String lanceur =row.getString("lanceur");
String sousAlerte = row.getString("SousAlerte");
String idLanceur = row.getString("idLanceur");
String idRecepteur = row.getString("Recepteur");
String dateCreation = row.getString("DateCreation");
AlertData alert = new AlertData(id, message, sousAlerte,lanceur, idLanceur, idRecepteur, dateCreation);
allAlerts.add(alert);
}
} catch (JSONException e) {
e.printStackTrace();
}
}
我希望有人可以帮助我。感谢您的帮助。
Ps:请原谅我的英语,我是法国人。
答案 0 :(得分:1)
我解决了我的问题。 添加方法utf8_encode()。
就足够了而不是那个
$alerts["Message"] = $row["Message"];
有必要替换
$alerts["Message"] = utf8_encode($row["Message"]);
因为字段“Message”在数据库中是text类型,所以Json不能直接编码文本。