Android JSON从url检索对象

时间:2015-10-14 13:19:10

标签: android json

我有脚本返回JSON这样

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

这是NDJSON的回复! 现在我试图从android中检索它,但我在jsonResult上得到null。 这是我在获取后使用的代码:

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

我在第一行得到空指针异常,因为jsonResult为null。 有什么问题?

这是我如何获取:

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

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

2 个答案:

答案 0 :(得分: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方法,以了解您的回复为何。

答案 1 :(得分: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);