我無法將使用sql查詢生成的php數(shù)組轉(zhuǎn)換為使用json_encode的JSONObject.我使用谷歌凌空來實(shí)現(xiàn)連接.
當(dāng)涉及單行結(jié)果時,我沒有遇到任何問題,但是當(dāng)有超過1行時,我在我的應(yīng)用程序中得到錯誤,這意味著我沒有真正收到JSONObject.
這是我的PHP代碼
if (mysql_num_rows($result) > 0) {
$rutina = array();
while($row = mysql_fetch_assoc($result))
{
$rutina[] = $row;
}}
我就是這樣回來的
echo json_encode($rutina);
我知道m(xù)ysql已被棄用,我很快就會遷移到mysqli.
將我的sql行數(shù)組轉(zhuǎn)換為JSONObject的正確方法是什么?
編輯:
這是我等待JSONObject的android代碼:
JsonObjectRequest solicitudRutina = new JsonObjectRequest(
Request.Method.POST, //metodo de solicitud
linkrutina, //url, se cambia en las variables
map,//el objeto JSON que contiene el usuario que intentaremos descargar
new Response.Listener<JSONObject>() { //el listener de la respuesta
@Override
public void onResponse(JSONObject response) { // si existe respuesta aca se cacha,
String temp= response.optString("sinexito");//sinexito tiene el mensaje de error de no encontrar el usuario
if(temp.equals("")){//si la rutina existe, iniciamos descarga
rutinaview.setText(response.toString());
//obtenerRutina(response);
}
else{
Context context = getApplicationContext();
CharSequence text = "Problema al descargar la rutina, posiblemente no exita una asignada";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
{
Context context = getApplicationContext();
CharSequence text = "Error con la base de datos.";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, duration);
toast.show();
}
}
});
VolleyApplication.getsInstance().getmRequestQueue().add(solicitudRutina);
我正在響應(yīng)錯誤的祝酒詞.我假設(shè)它是因為我沒有得到JSONObject?它僅適用于1行. 解決方法: 通常我使用這些就像要成功解析JSON對象那樣需要做一些事情,頁面頭必須有json作為MIME類型,所以任何其他代碼都可以輕松識別它.
<?php
header('Content-Type:application/json');
//Your Database query here...
$output = mysqli_fetch_all($rutina,MYSQLI_ASSOC);
echo json_encode($output);
它一直適用于我…不需要使用while循環(huán),它將輸出作為數(shù)據(jù)庫查詢找到的行的關(guān)聯(lián)數(shù)組 來源:https://www./content-2-276301.html
|