-1

これを行う際に多くの混乱が生じています。私がしなければならないことは、サーバーからの JSONP 応答を解析して表示することです。AndroidでJSONPレスポンスを解析することは可能ですか?

これが私の応答です。

{
    "Reference1":"String content",
    "Reference2":"String content",
    "Reference3":"String content",
    "Reference4":"String content"

}

ありがとうございました

4

3 に答える 3

1

私が多くのプロジェクトで行っていることは、最初にhttpストリームから読み取った文字列を以下のコードを使用してJSONObjectに変換することです。

JSONObject jsonOBJ=new JSONObject(jsonString);

次に、を使用jsonobject.getString("tag")して各タグを読み取ります。コードの場合、次のようになります。

String reference1=jsonobject.getString("Reference1");

ここで、referece1=の値String content

そして、これが私のhttpgetコードです。

String url="Your URL Goes Here";
DefaultHttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(url);
HttpResponse response;
try {
    try 
    {
      InetAddress i = InetAddress.getByName(url);
    } catch (UnknownHostException e1) {
      e1.printStackTrace();
    }
    response = httpclient.execute(httpget);
    HttpEntity entity = response.getEntity();
    if (entity != null) {
        InputStream instream = entity.getContent();
        String result= convertStreamToString(instream);
        stringContent=new StringContent(result);
        instream.close();
    }
} catch (ClientProtocolException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

そして以下はconvertStreamToStringブロックです

private static String convertStreamToString(InputStream is) 
{
    /*
     * To convert the InputStream to String we use the BufferedReader.readLine()
     * method. We iterate until the BufferedReader return null which means
     * there's no more data to read. Each line will appended to a StringBuilder
     * and returned as String.
     */
        BufferedReader reader = new BufferedReader(new InputStreamReader(is));
        StringBuilder sb = new StringBuilder();

        String line = null;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line + "\n");
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}
于 2012-04-24T11:35:23.243 に答える
0

このチュートリアルは、android.Hope での json の解析の非常に詳細なものだと思います。

于 2012-04-24T09:27:23.367 に答える
0

パディング自体は決して問題ではありません。すべての適切な JSON 解析ライブラリは、透過的に処理します。GSONライブラリを使用することを個人的にお勧めします。私は多くのプロジェクトでそれを使用してきましたが、不満を言うことは一度もありませんでした.

PS: 誤解しているかもしれませんが、パースと言うと、属性の値を取得する必要があり、パディングを保持する必要はないと思いますよね?

于 2012-04-24T09:22:42.437 に答える