0

Android で JSON 文字列を解析する際に問題が発生しました。文字列自体は問題ないように見えますが、少なくとも私が意図したものと同じように見えます。しかし、解析しようとするとクラッシュします。誰でも理由がわかりますか?ありがとう!

static InputStream is = null;
static JSONObject jObj = null;
static String json = "";

public JSONObject makeHttpRequest(String url, List<NameValuePair> params) {

        // Making HTTP request
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            if (params != null) {
                httpPost.setEntity(new UrlEncodedFormEntity(params));
            }

            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();
            Log.e("JSON", json);
        } catch (Exception e) {
            Log.e("Buffer Error", "Error converting result " + e.toString());
        }

        // try parse the string to a JSON object
        try {
            System.err.println("start try3"); //<--fine here
            System.err.println(json);         //<--json string looks good
            jObj = new JSONObject(json);     
            System.err.println("done try3");  //<--never outputs
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }

スタックトレース:

08-05 15:28:00.665: E/JSON パーサー (20009): データ org.json.JSONException の解析エラー: 値 [{"id":"3","bool_gets_sms":"0","picture_url":" none","email":"heather@me.com","cell":"12345","name":"Heather"},{"id":"7","bool_gets_sms":"0"," picture_url":"none","email":"alan@me.com","cell":"12335","name":"Alan"},{"id":"10","bool_gets_sms":" 0","picture_url":"none","email":"jenni@me.com","cell":"12345","name":"Jenni"},{"id":"11"," bool_gets_sms":"0","picture_url":"none","email":"jeff@me.com","cell":"12345","name":"Jeff"},{"id":"24","bool_gets_sms":" org.json.JSONArray 型の 0","picture_url":"none","email":"rob@me.com","cell":"12345","name":"Rob"}] は変換できませんJSONObjectに

4

2 に答える 2

0

あなたはそのようにする必要があります:

JsonElement el = new JsonParser().parse(json);
JSONObject obj= el.getAsJSONObject("the key you are looking for");

メソッドの正確な名前は、JSON 解析に使用するライブラリによって異なる場合があります。JSONObject ではなく、JSONArray で配列を取得するように注意してください。

于 2013-08-05T21:43:15.080 に答える