我使用下面的類來獲取一些JSON數據。奇怪的是,我無法僅從我需要測試應用程序的url(服務器端不是由我維護)解析JSON:如果您單擊this link,您將能夠在瀏覽器中看到JSON數據。但是當我嘗試以編程方式解析它時,它會引發JSONException。當試圖解析JSON數據時android 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;
}
}
看起來您實際上正在收到JBoss錯誤消息。我想添加一個'System.err.println(json);'看看你實際上試圖解析什麼...... – beny23
你的問題是在jObj = new JSONObject(json); ,檢查你的字符串'json'是否包含任何奇怪的符號或html。 –
是...值