如何在android中解析这个Json数组

时间:2016-01-07 09:51:15

标签: java android arrays json parsing

我有一个jsonArray,我想在我的Android应用程序中解析。

数组: -

[
   {
      "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托管here

我正在关注学习json解析的this教程,但本教程使用了jsonObject,我无法解析json数组。

与此不重复: - Sending and Parsing JSON Objects或此How to parse this JSON Array in android?

3 个答案:

答案 0 :(得分:2)

让我提供替代解决方案(各种)。现有代码的一个更简单的版本是:

更新的代码:

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 library。将此compile语句添加到模块的gradle文件的 dependencies 部分:compile 'com.squareup.okhttp:okhttp:2.5.0'。检查链接以获取更新版本。
  3. 示例代码使用if语句,考虑到并非每条记录都有相同的节点集。
  4. enter image description here

    enter image description here

答案 1 :(得分:1)

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");
}

答案 2 :(得分:1)

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不为null,那么它只会像这样运行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++) {}