我正在尝试解析来自this 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);
答案 0 :(得分:1)
您正在尝试使用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) {
....
}