2011-04-12 22 views
0

與JSONArray解析JSON我想一個json字符串到JSONArray轉換,但它拋出一個jsonexception無法在Android的

這是非常奇怪的,因爲錯誤的原因它給我看起來完全錯誤已經調試。

這是代碼的重要組成部分:

...

HttpResponse response = httpclient.execute(httppost); 
HttpEntity entity = response.getEntity(); 
InputStream is = entity.getContent(); 
// convert response to string 
try { 
     BufferedReader reader = new BufferedReader(
    new InputStreamReader(is, "utf-8")); 
    StringBuilder sb = new StringBuilder(); 
    String line = null; 
    while ((line = reader.readLine()) != null) { 
      sb.append(line + "\n"); 
    } 
    is.close(); 

     String result = sb.toString(); 
     result.trim(); //added by recommendation in comments     

     // parse json data 
    try { 
     JSONArray jArray = new JSONArray(result); **//this line jumps to the exception** 
      //Also tried 
      //JSONTokener tokener = new JSONTokener(result); 
      //JSONArray jArray = new JSONArray(tokener); //jumps to the exception too 

       for (int i = 0; i < jArray.length(); i++) { 
       JSONObject json_data = jArray.getJSONObject(i); 
      TextView info = (TextView)findViewById(R.id.info); 
      String sInfo = "id: " 
       + json_data.getInt("ID") 
       + ", descripció: " 
       + json_data.getString("DESC") 
       + ", nick: " 
       + json_data.getString("NICK") 
       + ", data de naixement: " 
       + json_data.getString("DATA_NEIX"); 
        info.setText(sInfo); 
       } 
      } catch (JSONException e) { 
       Log.e("log_tag", "Error parsing data " 
        + e.toString()); 
       } 

這是異常的詳細消息調試時,我得到:

A JSONArray text must start with '[' at character 1 of [{"ID":"1","NICK":"Jauuu","DESC":"Estic de proves amb php i mysql","FOTO":null,"DATA_NEIX":"1980-04-22","IDIOMA":null,"PAIS":"Espanya","GENERE":"H","ORIENTACIO":"heterosexu","ID_GRUP":null,"ESTAT":null,"ID_AMICS":null}] 

,你可以看到字符1確實有一個'['。我已經保證按位置觀看字符串位置。所以我無法確定真正的錯誤在哪裏。

請幫助我嗎?我完全迷失在這裏。提前致謝。

注意:現在我已經修剪了結果變量,並且得到了同樣的錯誤。這是它的價值:

[{"ID":"1","NICK":"Jauuu","DESC":"Estic de proves amb php i mysql","FOTO":null,"DATA_NEIX":"1980-04-22","IDIOMA":null,"PAIS":"Espanya","GENERE":"H","ORIENTACIO":"heterosexu","ID_GRUP":null,"ESTAT":null,"ID_AMICS":null}] 

臨時的解決方案和問題:

我已經解決了加入這一行的問題:

sb.deleteCharAt(0);

這裏:

... 
sb.deleteCharAt(0); 
String result = sb.toString(); 
result.trim(); 

... 

我不知道爲什麼,但我的迴應添加一個空字符(或類似的東西,因爲微調功能並沒有影響,但調試器還沒有顯示出任何東西)在我的StringBuilder的位置0。問題是這個異常信息令人困惑,並以某種方式告訴某些錯誤。

所有我曾在我的PHP文件中得到的回答是這樣的:

<?php 
mysql_connect("127.0.0.1","root",""); 
mysql_select_db("prova"); 

$q=mysql_query("SELECT * FROM perfil WHERE ID='".$_REQUEST['id']."'"); 
while($e=mysql_fetch_assoc($q)) 
     $output[]=$e; 

print(utf8_encode(json_encode($output))); 

mysql_close(); 
?> 

我現在已經解決了這個問題,但沒有人知道爲什麼這個PHP會將此空字符我的反應(它也增加了它在最後)?我是新來的PHP,所以也許這是一個愚蠢的問題,我只是想知道未來的情況。感謝所有幫助你評論的人。

+0

您發佈的JSON有效。我只是嘗試在Android上的「JSONArray」中解析它,它工作。我會仔細檢查字符串是否是您認爲的字符串,並且在開頭或結尾沒有任何額外的字符。 – 2011-04-12 09:54:20

+0

按照原樣發佈變量結果的值。修剪結果的值並檢查。 – sat 2011-04-12 09:59:56

+0

我已經做到了,但仍然存在問題。我已編輯帖子以向您顯示變量的值。 – Jauuu 2011-04-12 10:30:41

回答

2

至少我有最終的解決方案。

問題是我的PHP文件格式是utf-8與BOM字符。物料清單是什麼給我的問題。我所要做的就是用Notepad ++打開文件,然後選擇沒有BOM的編碼 - > UTF-8並保存文件。

而且這裏進一步簡化是我的Android代碼的新短,更容易版本:

try { 
    HttpClient httpclient = new DefaultHttpClient(); 
    HttpPost httppost = new HttpPost("http://10.0.2.2:8888/obtePerfil.php"); 
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); 
    HttpResponse response = httpclient.execute(httppost); 
    HttpEntity entity = response.getEntity(); 

    //this line here is what saves a lot of work 
    String result = EntityUtils.toString(entity, HTTP.UTF_8); 

    // parse json data 
    try { 
     JSONArray jArray = new JSONArray(result);       
     for (int i = 0; i < jArray.length(); i++) { 
     JSONObject json_data = jArray.getJSONObject(i); 
     TextView info = (TextView) findViewById(R.id.info); 
     String sInfo = "id: " + json_data.getInt("ID") 
       + ", descripció: " 
       + json_data.getString("DESC") + ", nick: " 
       + json_data.getString("NICK") 
       + ", data de naixement: " 
       + json_data.getString("DATA_NEIX"); 
     info.setText(sInfo); 
     } 
    } catch (Exception e) { 
     Log.e("log_tag", "Error parsing data " + e.toString()); 
     } 
} catch (Exception e) { 
     Log.e("log_tag", "Error in http connection "+ e.toString()); 
     } 

這就是全部。