解析数据时出错org.json.JSONException:字符0处的输入结束

我正在尝试解析来自此URL的 JSON数据。

但我收到这些错误:

03-27 16:48:21.019:E / Buffer Error(23717):转换结果java.lang.NullPointerException时出错

03-27 16:48:21.059:E / JSON Parser(23717):解析数据时出错org.json.JSONException:字符0处的输入结束

当我调试我的代码时; getJsonFromUrl()方法返回null jobject 。 这是我使用的JSONParser类 。 是什么导致错误?

 public class JSONParser { static InputStream iStream = null; static JSONArray jarray = null; static JSONObject jObj= null; static String json = ""; public JSONParser() { } public JSONObject getJSONFromUrl(String url) { // Making HTTP request DefaultHttpClient httpClient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); try { HttpResponse httpResponse = httpClient.execute(httpPost); HttpEntity httpEntity = httpResponse.getEntity(); InputStream is = httpEntity.getContent(); 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"); } iStream.close(); json = sb.toString(); } catch (Exception e) { Log.e("Buffer Error", "Error converting result " + e.toString()); } // try parsing the string to a JSON object try { if (json != null) { jObj = new JSONObject(json); } else { jObj = null; } } catch (JSONException e) { Log.e("JSON Parser", "Error parsing data " + e.toString()); } // return JSON String return jObj; } } 

我正在使用这些行从另一个类调用此方法。 (url参数定义在顶部)

  JSONParser jParser = new JSONParser(); final JSONObject jobject = jParser.getJSONFromUrl(url); 

您正在尝试使用HTTP POST方法而不是相应的GET方法( W3schools.com GET vs.POST )获取JSON内容,修改源代码以简化和修复HTTP请求

 DefaultHttpClient httpClient = new DefaultHttpClient(); HttpGet get = new HttpGet(url); try { HttpResponse httpResponse = httpClient.execute(get); String json = EntityUtils.toString(httpResponse.getEntity()); System.out.println(json); .... .... } catch (Exception e) { .... }