1

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

      }
  }
4

1 回答 1

1

使用 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();
}
于 2013-01-18T02:19:27.210 回答