0

私はかなり長い間JSONオブジェクトを解析しようとしてきました。ここにはこれに似た質問がたくさんありますが、うまくいく答えはありません。私のコードはどれも機密ではないので、ここに投稿します。

パブリッククラスJSONParser{

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

// constructor
public JSONParser() {

}

public JSONObject getJSONFromUrl(String url) {

    // Making HTTP request
    try {
        // defaultHttpClient
        DefaultHttpClient httpClient = new DefaultHttpClient();
        //HttpPost httpPost = new HttpPost(url);
            HttpGet httpget = new HttpGet(url);
        HttpResponse httpResponse = httpClient.execute(httpGet);
        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, "UTF-8"));
              //  is, "iso-8859-1"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;

        while ((line = reader.readLine()) != null) {

            sb.append(line);
        }
        is.close();


        json = sb.toString();
    } catch (Exception e) {
        Log.e("Buffer Error", "Error converting result " + e.toString());
    }

    // try parse the string to a JSON object
    try {
        JSONTokener tokener = new JSONTokener(json);
        jObj = new JSONObject(tokener);
    } catch (JSONException e) {
        Log.e("JSON Parser", "Error parsing data " + e.toString());
    }

    // return JSON String
    return jObj;

}

}

*投稿の代わりに編集されたGetが必要でした

4

3 に答える 3

0

あなたの何が悪いのかはわかりませんが、私が使っている私の作品と比較してみてください。入力文字0エラーが発生しましたが、これはサーバーサイドエラーであり、解析ではありませんでした。これは、返されたデータがおそらくJSONオブジェクトにエンコードできなかったことを意味します。正しく覚えていれば、サーバーは何も返さなかったと思います。基本的には解析しようとしていましたnothing。サーバーから何を取得しているかを確認します。

String result;
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("key", "value");
nameValuePairs.add(new BasicNameValuePair("key2", "value2");

try
{
    HttpClient httpclient = new DefaultHttpClient();

            // URL to POST to
    HttpPost httpreq = new HttpPost("www.sample.com/file.php");
    httpreq.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpclient.execute(httpreq);
    HttpEntity entity = response.getEntity();
    InputStream is = entity.getContent();

    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();

    result = sb.toString();
            /* if you print 'result' you should see valid data 
               if your server is working */
            // System.out.println(result); 
}
catch (Exception e)
{
    // handle what went wrong
}

JSONArray jArray = new JSONArray(result);

if (jsonArray != null)
{
   for (int i = 0; i < jsonArray.length(); i++)
   {
       JSONObject json_data;
       try
       {
           json_data = jsonArray.getJSONObject(i);
           String value = json_data.getString("json_key_here");                
       }
       catch (JSONException e)
       {
            // handle what went wrong
       }
   }
}
于 2013-02-27T02:52:13.033 に答える
0

小さなテストアプリを作って実行しました。HTTPPostは何も返しませんが、HTTPGetに切り替えると、有効な応答が得られます。

その後、配列の最初の要素に「名前」がないため、を呼び出すとc.getString("name")、外部ブロックでキャッチしているように見えるJSONExceptionが生成されます。呼び出しごとgetStringに、次のような例外処理を追加する必要があります。

String name = null;
try {
name = c.getString("name");
} catch(JSONException e) {
//name is missing!
name = "";
}
于 2013-02-27T05:23:23.550 に答える
0

エンティティを取得し、一度に1行ずつエンティティを読み取るBufferedReaderに変換し、それを文字列に変換し、文字列をJSONTokenerに変換し、最後にトークナーを使用してJSONObjectを作成する理由がわかりません。

これを行う簡単な方法は次のとおりです。

String entityString = EntityUtils.toString(httpResponse.getEntity(), HTTP.UTF_8);
JSONObject json = new JSONObject(entityString);

それが例外をスローする場合は、出力でそれをキャッチします。

} catch (Exception e) {
    e.printStackTrace();
}

そして、その痕跡を見せてください。

于 2013-02-27T05:24:35.620 に答える