尝试解析JSON数据时出现android JSONException

时间:2013-01-03 10:12:50

标签: android json exception

我使用下面的类来获取一些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;

      }
  }

1 个答案:

答案 0 :(得分:1)

使用BufferedReader方法将获取该页面的HTML源代码,这就是为什么你会看到像

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();
}