2013-05-17 75 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