Reputation: 11608
I use the class below to get some JSON data. The strange thing is, I can't parse JSON only from the url I need to test the app (server-side not maintained by me): if you click on this link, you will be able to see JSON data in your browser. But when I try to parse it programmatically, it throws a 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
I tried to test it with http://ip.jsontest.com/ and http://api.androidhive.info/contacts, it works nicely! Exception is only thrown while trying to parse JSON from my 1st link. I thought it could be a server problem, but I'm able to see JSON data with a browser.. just can't explain that.
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;
}
}
Upvotes: 1
Views: 1731
Reputation: 462
Using the BufferedReader approach will fetch you the HTML source of that page, which is why you see HTML tags like < html>< head>< title> in your string. Instead, use EntityUtils to get the JSON string:
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();
}
Upvotes: 1