簡體   English   中英

如何在Android中解析此Json數組

[英]How to parse this Json Array in android

我有一個想在我的Android應用程序中解析的jsonArray。

數組:-

[
   {
      "id": 96905,
      "category": "topup",
      "detail": "Full talktime of Rs.55 + 1 local airtel SMS free for 1 day",
      "price": 55,
      "keywords": "topup",
      "updated": "2016-01-07 00:16:23.0",
      "validity": "7 days",
      "service": "Airtel",
      "sourceUri": "https://pay.airtel.com/online-payments/recharge.jsp",
      "circle": "Assam",
      "talktime": 55
   },

   {
      "id": 90397,
      "category": "topup",
      "price": 510,
      "keywords": "topup",
      "updated": "2016-01-07 00:16:23.0",
      "service": "Airtel",
      "sourceUri": "https://pay.airtel.com/online-payments/recharge.jsp",
      "circle": "Assam",
      "talktime": 520
   },
   {
      "id": 90399,
      "category": "topup",
      "price": 1000,
      "keywords": "topup",
      "updated": "2016-01-07 00:16:23.0",
      "service": "Airtel",
      "sourceUri": "https://pay.airtel.com/online-payments/recharge.jsp",
      "circle": "Assam",
      "talktime": 1020
   }]

我的Android代碼:-

的AsyncTask: -

private class DownloadJSON extends AsyncTask<Void, Void, Void> {
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressDialog = new ProgressDialog(MainActivity.this);
            mProgressDialog.setTitle("Android JSON Parse Tutorial");
            mProgressDialog.setMessage("Loading...");
            mProgressDialog.setIndeterminate(false);
            mProgressDialog.show();
        }

        @Override
        protected Void doInBackground(Void... params) {
            // Create an array
            arraylist = new ArrayList<HashMap<String, String>>();
            try {
                JSONObject jo;
               JSONArray ja2 = JSONfunctions.getJSONfromURL("http://app.ireff.in:9090/IreffWeb/android?service=airtel&circle=assam");

                for (int i = 0; i < ja2.length(); i++) {
                    HashMap<String, String> map = new HashMap<String, String>();
                    jo = ja2.getJSONObject(i);   
                    map.put("rank", jo.getString("price"));
                    map.put("country", jo.getString("validity"));
                    map.put("population", jo.getString("talktime"));
                    arraylist.add(map);
                }
            } catch (JSONException e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return null;
        }

        @Override
        protected void onPostExecute(Void args) {
            listview = (ListView) findViewById(R.id.listview);
            adapter = new ListViewAdapter(MainActivity.this, arraylist);
            listview.setAdapter(adapter);
            mProgressDialog.dismiss();
        }
    }

JsonFunctions.java

public class JSONfunctions {

    public static JSONArray getJSONfromURL(String url) {
        InputStream is = null;
        String result = "";
        JSONArray jArray = null;

        // Download JSON data from URL
        try {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost httppost = new HttpPost(url);
            HttpResponse response = httpclient.execute(httppost);
            HttpEntity entity = response.getEntity();
            is = entity.getContent();

        } catch (Exception e) {
            Log.e("log_tag", "Error in http connection " + e.toString());
        }

        // Convert response to string
        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();
            result = sb.toString();
        } catch (Exception e) {
            Log.e("log_tag", "Error converting result " + e.toString());
        }

        try {

            jArray = new JSONArray(result);
        } catch (JSONException e) {
            Log.e("log_tag", "Error parsing data " + e.toString());
        }

        return jArray;
    }
}

我得到的錯誤:-

Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'int org.json.JSONArray.length()' on a null object reference
at com.androidbegin.jsonparsetutorial.MainActivity$DownloadJSON.doInBackground(MainActivity.java:67)
at com.androidbegin.jsonparsetutorial.MainActivity$DownloadJSON.doInBackground(MainActivity.java:39)
at android.os.AsyncTask$2.call(AsyncTask.java:292)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231) 
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112) 
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587) 
at java.lang.Thread.run(Thread.java:818) 

json托管在這里

我正在按照教程學習json解析,但是本教程使用jsonObject,但是我無法解析json數組。

不是重復的內容:- 發送和解析JSON對象,或者如何在android中解析此JSON數組?

讓我提供另一種解決方案。 現有代碼的簡單得多的版本是:

更新的代碼:

private class DownloadJSON extends AsyncTask<Void, Void, Void> {

    ProgressDialog mProgressDialog;

    ArrayList<HashMap<String, String>> arraylist = new ArrayList<>();

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

        mProgressDialog = new ProgressDialog(TestListActivity.this);
        mProgressDialog.setTitle("Android JSON Parse Tutorial");
        mProgressDialog.setMessage("Loading...");
        mProgressDialog.setIndeterminate(false);
        mProgressDialog.show();
    }

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

        String url = "http://app.ireff.in:9090/IreffWeb/android?service=airtel&circle=assam";

        OkHttpClient okHttpClient = new OkHttpClient();
        okHttpClient.setConnectTimeout(30, TimeUnit.SECONDS);
        okHttpClient.setReadTimeout(30, TimeUnit.SECONDS);
        okHttpClient.setRetryOnConnectionFailure(true);

        Request request = new Request.Builder()
                .url(url)
                .build();
        Call call = okHttpClient.newCall(request);

        try {
            Response response = call.execute();
            String strResult = response.body().string();
            JSONArray JARoot = new JSONArray(strResult);

            for (int i = 0; i < JARoot.length(); i++) {
                JSONObject JORoot = JARoot.getJSONObject(i);

                HashMap<String, String> map = new HashMap<>();

                if (JORoot.has("category") && JORoot.getString("category").equals("topup"))   {

                    if (JORoot.has("id")) {
                        map.put("id", JORoot.getString("id"));
                    }

                    if (JORoot.has("category")) {
                        map.put("category", JORoot.getString("category"));
                    }

                    if (JORoot.has("detail")) {
                        map.put("detail", JORoot.getString("detail"));
                    } else {
                        map.put("detail", null);
                    }

                    if (JORoot.has("price")) {
                        map.put("price", JORoot.getString("price"));
                    }

                    /** ADD THE COLLECTED DATA TO THE ARRAY LIST **/
                    arraylist.add(map); /* THE DATA WILL ONLY BE ADDED IF THE CATEGORY = "topup" */
                }
            }
        } catch (IOException | JSONException e) {
            e.printStackTrace();
        }

        return null;
    }

    @Override
    protected void onPostExecute(Void aVoid) {
        super.onPostExecute(aVoid);

        ListView testList = (ListView) findViewById(R.id.testList);
        TestListAdapter adapter = new TestListAdapter(TestListActivity.this, arraylist);
        testList.setAdapter(adapter);

        mProgressDialog.dismiss();
    }
}

private class TestListAdapter extends BaseAdapter {

    Activity activity;

    // LAYOUTINFLATER TO USE A CUSTOM LAYOUT
    LayoutInflater inflater = null;

    // ARRAYLIST TO GET DATA FROM THE ACTIVITY
    ArrayList<HashMap<String, String>> arrItem;

    public TestListAdapter(Activity activity, ArrayList<HashMap<String, String>> arrItem) {

        this.activity = activity;

        // CAST THE CONTENTS OF THE ARRAYLIST IN THE METHOD TO THE LOCAL INSTANCE
        this.arrItem = arrItem;

        // INSTANTIATE THE LAYOUTINFLATER
        inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    }

    @Override
    public int getCount() {
        return arrItem.size();
    }

    @Override
    public Object getItem(int position) {
        return arrItem.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public void notifyDataSetChanged() {
        super.notifyDataSetChanged();
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {

        // A VIEWHOLDER INSTANCE
        ViewHolder holder;

        // CAST THE CONVERTVIEW IN A VIEW INSTANCE
        View vi = convertView;

        // CHECK CONVERTVIEW STATUS
        if (convertView == null)    {
            // CAST THE CONVERTVIEW INTO THE VIEW INSTANCE vi
            vi = inflater.inflate(R.layout.test_item, null);

            // INSTANTIATE THE VIEWHOLDER INSTANCE
            holder = new ViewHolder();

            /*****  CAST THE LAYOUT ELEMENTS    *****/

            /* TOP (PRIMARY) ELEMENTS */
            holder.txtPrice = (TextView) vi.findViewById(R.id.txtPrice);
            holder.txtDetail = (TextView) vi.findViewById(R.id.txtDetail);

            // SET THE TAG TO "vi"
            vi.setTag(holder);
        } else {
            // CAST THE VIEWHOLDER INSTANCE
            holder = (ViewHolder) vi.getTag();
        }

        if (arrItem.get(position).get("price") != null)    {
            String strPrice = arrItem.get(position).get("price");
            holder.txtPrice.setText("PRICE:  " + strPrice);
        }

        if (arrItem.get(position).get("detail") != null)   {
            String strDetail = arrItem.get(position).get("detail");
            holder.txtDetail.setText("DETAIL: " + strDetail);
        } else {
            holder.txtDetail.setText("DETAIL: NA");
        }

        return vi;
    }

    private class ViewHolder    {

        /* TOP (PRIMARY) ELEMENTS */
        TextView txtPrice;
        TextView txtDetail;
    }
}

為了完整起見,我還包括了adapter的代碼。 這是一個簡單的實現。 根據您的要求進行清理/優化/自定義。

  1. 這段代碼在發布之前已經過測試(請參閱底部的日志截圖)
  2. 這使用OkHttp庫 將此compile語句添加到模塊的gradle文件的dependencies部分中: compile 'com.squareup.okhttp:okhttp:2.5.0' 檢查鏈接以獲取更新的版本。
  3. 示例代碼使用if語句,考慮到並非每個記錄都具有相同的節點集。

在此處輸入圖片說明

在此處輸入圖片說明

jsonResponse="";
for(int i = 0; i<response.length(); i++) {
    JSONObject person = (JSONObject) response.get(i);

    String id = person.getString("id");
    String category = person.getString("category");
}

您的BufferReader無法在您的類JSONfunctions中按預期方式工作,請在您的類中進行一些更改,它看起來應該像

JSONfunctions.java

public class JSONfunctions {

public static JSONArray getJSONfromURL(String url) {
    InputStream is = null;
    String result = "";
    JSONArray jArray = null;

    // Download JSON data from URL
    try {
        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(url);
        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    } catch (Exception e) {
        Log.e("log_tag", "Error in http connection " + e.toString());
    }


       StringBuffer sb = new StringBuffer("");
    try {
        URL urls = new URL(url);
        URLConnection urlConnection;
        urlConnection = urls.openConnection();
        InputStream in = urlConnection.getInputStream();
        BufferedReader br=new BufferedReader(new InputStreamReader(in));
         String line = "";
            while ((line = br.readLine()) != null) {
                sb.append(line);
            }
            System.out.println(sb);
            result=sb.toString();
    } catch (IOException e) {}
      catch (Exception e) {}
    try {

        jArray = new JSONArray(result);
    } catch (JSONException e) {
        Log.e("log_tag", "Error parsing data " + e.toString());
    }

    return jArray;
   }
  }

並避免異常檢查是否JSONArray不為空則只有它去跑for這樣的循環:

 JSONArray ja2 =   JSONfunctions.getJSONfromURL("http://app.ireff.in:9090/IreffWeb/android?  service=airtel&circle=assam");
 if(ja2!=null)
            for (int i = 0; i < ja2.length(); i++) {}

暫無
暫無

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

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