2013-10-29 85 views
0

我得到這個錯誤使用php-mysql和json,認真我花了2天,所以這裏是我的代碼Error解析data.org.json.JSONException類型java.lang.String的值不能轉換爲JSONArray

require "includes/connexion.php"; 
$requete="SELECT * FROM contacts;"; 
$rep=$pdo->query($requete); 

while($data=$rep->fetch(PDO::FETCH_ASSOC)){ 
$sortie[]=$data; 
} 
print(json_encode($sortie)); 
$rep->closeCursor(); 

這裏是在結果參數的Java代碼和jsonArray的部分包含的值(從控制檯):

 [{"id":"1","nom":"Fedson Dorvilme","email":"[email protected]","phone":"34978238","img":"ic_launcher"},{"id":"2","nom":"Darlene Aurelien","email":"[email protected]","phone":"34171191","img":"ic_launcher"}] 



     JSONArray array = new JSONArray(result); 


     for (int i = 0; i < array.length(); i++) { 
      JSONObject json_data = array.getJSONObject(i); 

      Log.i("MyLogFlag", "Nom Contact: " + json_data.getString("nom")); 
      returnString = "\n\t" + array.getJSONArray(i); 
      System.out.println(" ********** RS [ "+returnString+" ]****************"); 

     } 
    } catch (Exception e) { 
     Log.e("log_Exception_tag", "Error parsing data " + e.toString()); 

    } 

在此先感謝您的幫助

回答

1

這是你的json s tructure:

[ 
    { 
     "id": "1", 
     "nom": "Fedson Dorvilme", 
     "email": "[email protected]", 
     "phone": "34978238", 
     "img": "ic_launcher" 
    }, 
    { 
     "id": "2", 
     "nom": "Darlene Aurelien", 
     "email": "[email protected]", 
     "phone": "34171191", 
     "img": "ic_launcher" 
    } 
] 

從Java代碼:

JSONArray array = new JSONArray(result); // OK 


    for (int i = 0; i < array.length(); i++) { 
     JSONObject json_data = array.getJSONObject(i); // OK 

     returnString = "\n\t" + array.getJSONArray(i); // ??? wrong!! 
    } 

您嘗試從數組,但它的JSONObject得到陣列。

有道:

JSONArray gb = new JSONArray(str); 

    for (int j = 0; j < gb.length(); j++) { 
     JSONObject element = gb.getJSONObject(j); 

     int id = element.getInt("id"); 
     int phone = element.getInt("phone"); 
     String nom = element.getString("nom"); 
     String email = element.getString("email"); 
     String img = element.getString("img");   
    } 
相關問題