我使用下面的类来获取一些 JSON 数据。奇怪的是,我不能只从我需要测试应用程序的 url 解析 JSON(服务器端不是由我维护的):如果你点击 this link ,您将能够在浏览器中看到 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;
}
}
最佳答案
使用 BufferedReader 方法将为您获取该页面的 HTML 源代码,这就是为什么您会在字符串中看到像 < html>< head> < title> 这样的 HTML 标记。相反,使用 EntityUtils 获取 JSON 字符串:
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
try {
HttpResponse httpResponse = httpClient.execute(httpGet);
HttpEntity httpEntity = httpResponse.getEntity();
int status = httpResponse.getStatusLine().getStatusCode();
if (status == HttpStatus.SC_OK) {
String jsonString = EntityUtils.toString(httpEntity);
try {
JSONObject jsonObject = new JSONObject(jsonString);
} catch (JSONException e) {
e.printStackTrace();
}
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
关于尝试解析 JSON 数据时出现 android JSONException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14136759/