以下のクラスを使用して、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;
}
}