2015-10-14 59 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为空 –