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 に答える