2015-10-14 98 views
0

檢索對象我有這樣Android的JSON從URL

{"a":"something","b":"something"} 
{"a":"something1","b":"something1"} 

腳本返回JSON這是NDJSON響應! 現在我試圖從android中檢索它,但是我在jsonResult上得到了null。 這是我使用的代碼讀取後:

JSONObject jsonResponse = new JSONObject(jsonResult); 
JSONArray jsonMainNode = new JSONArray(jsonResponse); 

我得到的第一行空指針異常,因爲jsonResult爲空。 有什麼不對?

這是我如何獲取:

HttpClient httpclient = new DefaultHttpClient(); 
HttpGet httpget = new HttpGet(url); 

HttpResponse response = httpclient.execute(httpget); 
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString(); 
+1

你可以發佈你的'jsonResult'?你有這個錯誤,因爲'jsonResult'爲null – ThomasThiebaud

+0

發佈了更多的代碼..你能分析哪些是錯誤的嗎? –

+0

也許發佈此方法將幫助我們瞭解更多'inputStreamToString' – kabuto178

回答

0

檢查結果爲空使用它

HttpClient httpclient = new DefaultHttpClient(); 
HttpGet httpget = new HttpGet(params[0]); 

HttpResponse response = httpclient.execute(httpget); 

jsonResult = inputStreamToString(response.getEntity().getContent()).toString(); 

if(result != null) { 
    JSONObject jsonResponse = new JSONObject(jsonResult); 
    JSONArray jsonMainNode = new JSONArray(jsonResponse); 
} else { 
    //Do something 
} 

現在你必須檢查你的請求或inputStreamToString方法之前知道爲什麼你有一個空響應。

0

試試這個:

int status = response.getStatusLine().getStatusCode(); 
HttpEntity httpEntity = response.getEntity(); 
      is = httpEntity.getContent(); 

BufferedReader reader = new BufferedReader(new InputStreamReader(is, HTTP.UTF_8), 8); 
      StringBuilder sb = new StringBuilder(); 
      String line = null; 
      while ((line = reader.readLine()) != null) 
      { 
       sb.append(line + "\n"); 
      } 
      is.close(); 
      String json = sb.toString(); 
JSONObject jObj = new JSONObject(json); 
+0

什麼是「是」?我如何定義它? –

+0

is = inputstream – ThomasThiebaud

+0

將HTTP.UTF_8更改爲「UTF_8」..但仍json爲空 –