我使用下面的类来获取一些 JSON 数据。奇怪的是,我不能仅从我需要测试应用程序的 url 解析 JSON(服务器端不是我维护的):如果您单击此链接,您将能够在浏览器中看到 JSON 数据。但是当我尝试以编程方式解析它时,它会抛出一个 JSONException。
01-03 11:08:23.615: E/JSON Parser(19668): Error parsing data org.json.JSONException: Value <html><head><title>JBoss of type java.lang.String cannot be converted to JSONObject
我尝试使用http://ip.jsontest.com/ 和http://api.androidhive.info/contacts对其进行测试,效果很好!仅在尝试从我的第一个链接解析 JSON 时引发异常。我认为这可能是服务器问题,但我可以用浏览器查看 JSON 数据.. 只是无法解释。
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
/* default constuctor*/
public JSONParser() {
}
public JSONObject getJSONFromUrl(String url) {
/* get JSON via http request */
try {
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();
}
try {
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");
}
is.close();
json = sb.toString();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
/* try to parse the string to JSON Object*/
try {
jObj = new JSONObject(json);
} catch (JSONException e) {
Log.e("JSON Parser", "Error parsing data " + e.toString());
}
/* return JSON String */
return jObj;
}
}