簡體   English   中英

解析時Android JSON空指針異常

[英]Android JSON null pointer Exception while parsing

我是android的初學者。我正在制作一個與web服務相關的應用程序。我通過擊url獲取json,並且想在listview中顯示。我嘗試了很多方法但沒有結果。我得到了json異常。請幫助我這是我的JSON:

    [
    [
    {
    "id":"9637",
    "country":"Australia",
    "time":"14:00",
    "type":"country",
    "status":"good"
    },
    {
    "id":"9638",
    "country":"india",
    "time":"16:00",
    "type":"country",
    "status":"good"
    }
    ]
    ]
code:
class Response extends AsyncTask<Void, Void, Void> {

        @Override
        protected Void doInBackground(Void... params) {

            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            try {
                HttpResponse httpResponse = httpClient.execute(httpPost);
                HttpEntity httpEntity = httpResponse.getEntity();
                jsonResponse = EntityUtils.toString(httpEntity);

            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return null;
        }

protected void onPostExecute(Void result) {

            Toast.makeText(MainActivity.this,jsonResponse,Toast.LENGTH_SHORT).show();
            try {
                JSONArray jsonArray=new JSONArray(jsonResponse);
                for(int i=0;i<jsonArray.length();i++)
                {
                    Toast.makeText(MainActivity.this,""+jsonArray.length(),Toast.LENGTH_SHORT).show();

                }
            //  JSONArray jsonArray=jsonObject.get


            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }



            super.onPostExecute(result);
        }

我認為這段代碼是正確的:

        try {
            JSONArray json=new JSONArray(jsonResponse);
            JSONArray jsonArray=json.getJSONArray(0);
            for(int i=0;i<jsonArray.length();i++)
            {
                Toast.makeText(MainActivity.this,""+jsonArray.length(),Toast.LENGTH_SHORT).show();

            }
        //  JSONArray jsonArray=jsonObject.get


        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

因為您的JSON響應是一個數組數組。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM