2015-10-20 18 views
-1

這是我的PHP請求:如何在ANDROID中使用JSON?

<?php 

// parametri del database 
$db_host = "localhost"; 
$db_user = "unisadb"; 
$db_password = ""; 
$db_name = "my_unisadb"; 
$db = mysql_connect($db_host, $db_user1, $db_password); 
if ($db == FALSE) 
    die ("Errore nella connessione. Verificare i parametri..."); 
mysql_select_db($db_name, $db) 
    or die ("Errore nella selezione del database. Verificare i parametri..."); 
$q = mysql_query("SELECT * FROM Utente"); 
while($e=mysql_fetch_assoc($q)) 
     $output[]=$e; 

print(json_encode($output)); 
mysql_close(); 

?> 

,這是JSON響應

[ 
{ 
    "idUtente": "1", 
    "Nome": "Roberto", 
    "Cognome": "D'Antuono", 
    "Valutazione": "0" 
}, 
{ 
    "idUtente": "2", 
    "Nome": "Luca ", 
    "Cognome": "Carbone", 
    "Valutazione": "90" 
} 
] 

你能幫我一個指南或順序「如何」通過這個JSON獲取數據?

+3

顯示代碼你試圖解析發佈的json。因爲json很容易將你發佈的問題解析出來 –

回答

1

也許最簡單和最好的方法是使用Gson或Jackson。你可以從這裏http://mvnrepository.com/artifact/com.google.code.gson/gson/2.3.1下載GSON和所有你需要的是你的JSON結構創建的域對象,像

public class Utente { 
private int idUtente; 
private String Nome; 
private int Cognome; 
private double Valutazione; 

... geters and setters... 

} 

和反序列化這樣的:

GSON GSON =新GsonBuilder()創建( ); Utente utente = gson.fromJson(response.toString(),Utente.class);

0

假設您想從json獲取全名。所以代碼會是這樣的。

JSONArray jsonArray = new JSONArray(json_string); // download and pass the json string here 
    String []name = new String[jsonArray.length()]; 
    for(int p=0;p<jsonArray.length();p++){ 
     try { 
      JSONObject singleIndexObject = jsonArray.getJSONObject(p); 
      name[p] = singleIndexObject.getString("Nome"); // Name is the name of the key from your Json String 
      // Add other value same as previous . 
     } catch (JSONException e) { 
      e.printStackTrace(); 
     } 
    } 
0

JSONArray永不爲空。您必須下載並將Json格式的字符串傳遞給參數。對於下載,你可以使用Volley