我在解析 JSON 时遇到了一些问题。主要思路是通过url在SQL数据库中查找数据:
JSONObject json = jParser.getJSONFromUrl(url + "?numer=" + number);
然后解析它。一切都很好,直到我想找到数据库中不存在的数据。网页返回“[]”,我的 android 应用返回错误“org.json.JSONArray 类型的值 [] 无法转换为 JSONObject”。这是我使用的一段代码。
public JSONObject getJSONFromUrl(String url) {
Log.e("Znacznik", "Przed żądaniem http");
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Log.e("Znacznik", "Przed odczytem bufora");
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "utf8"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
Log.e("Znacznik", "Przed parsowaniem");
// try parse the string to a JSON object
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
Log.e("Znacznik", "Przed returnem: "+jObj);
// return JSON String
return jObj;
}