2

JSONデータをAndroidに解析する際に問題があります

  • 私が直面している問題について説明しました。これを克服する方法についてのアイデア

最初に、URLからのJSONを使用しました

URL:: http://54.218.73.244:8084/

JSONParser.java

public class JSONParser {

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

    // constructor
    public JSONParser() {

    }

    public JSONArray getJSONFromUrl(String url) {

        // Making HTTP request
        try {
            // defaultHttpClient
            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 parse the string to a JSON object
        try {
            jObj = new JSONArray(json);
        } catch (JSONException e) {
            Log.e("JSON Parser", "Error parsing data " + e.toString());
        }

        // return JSON String
        return jObj;

    }
}

AndroidJSONParsingActivity.java

    public class AndroidJSONParsingActivity extends Activity {

        // url to make request
        private static String url = "http://54.218.73.244:8084/";
        private HashMap<Integer, String> contentsMap = new HashMap<Integer, String>();


        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.on

Create(savedInstanceState);
        setContentView(R.layout.activity_main);
            // Creating JSON Parser instance
            JSONParser jParser = new JSONParser();

            // getting JSON string from URL
            JSONArray json = jParser.getJSONFromUrl(url);

            try {
                for (int i = 0; i < json.length(); i++) {
                    JSONObject c = json.getJSONObject(i);

                    // Storing each json item in variable
                    int id = c.getInt("id");
                    String name = c.getString("content");

                    contentsMap.put(id, name);
                }
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    @Override
    protected void onResume() {
        super.onResume();

        TextView textView=(TextView) findViewById(R.id.textView1);
        textView.setText(contentsMap.get(1));

        textView=(TextView) findViewById(R.id.textView2);
        textView.setText(contentsMap.get(2));


    }
}

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" 
    android:padding="10sp">

    <TextView
        android:id="@+id/textView1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="10sp"
        android:text="TextView1" />

    <TextView
        android:id="@+id/textView2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:padding="10sp"
        android:text="TextView2" />

</LinearLayout>

出力::

上記のコードの出力は次のとおりです。

図-1


次に、URL を次のように変更します

URL:: http://54.218.73.244:7003/

そして、コードの他の部分を変更することなく

今、私はエラー画面を取得します

図-2


エラーログ

08-10 09:45:41.731: E/JSON Parser(448): Error parsing data org.json.JSONException: Value Cannot of type java.lang.String cannot be converted to JSONArray
08-10 09:45:41.737: D/AndroidRuntime(448): Shutting down VM
08-10 09:45:41.737: W/dalvikvm(448): threadid=1: thread exiting with uncaught exception (group=0x40015560)
08-10 09:45:41.772: E/AndroidRuntime(448): FATAL EXCEPTION: main
08-10 09:45:41.772: E/AndroidRuntime(448): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.json_web/com.example.json_web.AndroidJSONParsingActivity}: java.lang.NullPointerException
08-10 09:45:41.772: E/AndroidRuntime(448):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1647)
08-10 09:45:41.772: E/AndroidRuntime(448):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1663)
08-10 09:45:41.772: E/AndroidRuntime(448):  at android.app.ActivityThread.access$1500(ActivityThread.java:117)
08-10 09:45:41.772: E/AndroidRuntime(448):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:931)

エラーによる私の分析::

  • 解析中にエラーが発生しました 文字列を JSONArray に変換できません
  • このエラーを解決するには?

  • URL::http://54.218.73.244:8084/

私が得るJSON応答は:: [{"id":1,"content":"Hello"},{"id":2,"content":"World"}]

  • URL::http://54.218.73.244:7003/

私が得るJSON応答は::[{"id":1,"content":"Hello"},{"id":2,"content":"World"}]

JSON の構造は同じです。ブラウザの URL を使用して確認してください。


ありがとう、


4

3 に答える 3

2

のサーバーはリクエストhttp://54.218.73.244:7003/をサポートしていません。POST

したがって、サーバーがPOSTリクエストを受け入れるようにするか、JSONParserクラスの次の行を変更してください。

//HttpPost httpPost = new HttpPost(url); //Remove this and replace with the below

HttpGet httpGet = new HttpGet(url);
于 2013-08-10T05:43:33.353 に答える
0

データ org.json.JSONException の解析中にエラーが発生しました: java.lang.String 型の値を JSONArray に変換できません

私が見ることができる限り、エラーログから、解析しようとしている JSON 文字列が無効であることがわかります。

問題は実際にはコードとは関係ありません。サーバーから適切な JSON 応答が得られることを確認してください。

于 2013-08-10T05:47:18.880 に答える