2013-05-17 60 views
0

我想解析我的應用程序中的JSON。Logcat上的JSON錯誤。不能找到從Logcat錯誤是什麼

我的JSONParser.java如下。

public class JSONParser { 
    static InputStream is = null; 
    static JSONObject jObj = null; 
    static String json = ""; 


    public JSONObject getJSONFromUrl(String url, List<NameValuePair> params) { 

    // Making HTTP request 
    try { 
     // defaultHttpClient 
     DefaultHttpClient httpClient = new DefaultHttpClient(); 
     HttpPost httpPost = new HttpPost(url); 
     httpPost.setEntity(new UrlEncodedFormEntity(params)); 

     HttpResponse httpResponse = httpClient.execute(httpPost); 
     HttpEntity httpEntity = httpResponse.getEntity(); 
     is = httpEntity.getContent(); 

    } catch (UnsupportedEncodingException e) { 
     e.printStackTrace(); 
    } catch (ClientProtocolException e) { 
     e.printStackTrace(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 

    try { 
     BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8); 
     StringBuilder sb = new StringBuilder(); 
     String line = null; 
     while ((line = reader.readLine()) != null) { 
      sb.append(line + "n"); 
     } 
     is.close(); 
     json = sb.toString(); 
     Log.e("JSON", json); 
    } catch (Exception e) { 
     Log.e("Buffer Error", "Error converting result " + e.toString()); 
    } 

    // try parse the string to a JSON object 
    try { 
     jObj = new JSONObject(json); 
    } catch (JSONException e) { 
     Log.e("JSON Parser", "Error parsing data " + e.toString()); 
    } 

    // return JSON String 
    return jObj; 

} 

}

我的JSON從這裏 http://ketozen.com/ketorecipes/

這裏發送到該設備是引擎收錄輸出 http://pastebin.com/s1M8HzNr

這是在我的日誌。 http://pastebin.com/QTUphjeR

難道有人請澄清問題出在哪裏?

+0

是getJSONFromUrl在UI線程上運行? – Blackbelt

+0

你的logcat沒問題。但是你應該刪除'Log.e(「JSON」,json);'。爲什麼在成功結果之後記錄錯誤? – vorrtex

+0

printStackTrace而不是日誌e.toString。 – njzk2

回答

3
sb.append(line + "n"); 

可能是你的意思是寫

sb.append(line + "\n"); 

而且EntityUtils具有靜態方法toString(entity))。你可以直接在您的String 這樣

HttpEntity httpEntity = httpResponse.getEntity(); 
String jsonString = EntityUtils.toString(httpEntity); 

然後

try { 
     jObj = new JSONObject(jsonString); 
} catch (JSONException e) { 
     Log.e("JSON Parser", "Error parsing data " + e.toString()); 
} 
+0

嘿,謝謝。我是初學者,所以不知道Entityutils。我會在我的代碼中附加這個。還要感謝您捕獲\ n錯誤。我完全沒有注意到它。你對代碼有什麼建議嗎? – Sam

+1

使用EntityUtils而不是BufferRead,這次:) – Blackbelt