简体   繁体   中英

How to filter json objects from an array by ID and pass to recyclerview

I have a json file that looks like the json structure given below, now i want all the objects with item_id=2 and pass them to recyclerview. Can anybody please solve my problem? Thanks in advance

My json file structure that looks like this

{
"iceberg": [
{
  "item_id": 1,
  "Quote": "some quote text"
},
{
  "item_id": 2,
  "Quote": "some quote text"

},
{
  "item_id": 1,
  "Quote": "some quote text"
},
{
  "item_id": 2,
  "Quote": "some quote text"
}
]}
private void parseJSON() {
       String url = "https://example.com/files/file.json";
       int itemId = 0 //declare int for current item id

       JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null,
               new Response.Listener<JSONObject>() {
                   @Override
                   public void onResponse(JSONObject response) {
                       try {
                           JSONArray jsonArray=response.getJSONArray("iceberg");

                           for (int i = 0; i < jsonArray.length(); i++) {
                               JSONObject hit = jsonArray.getJSONObject(i);

                               //set current item id
                               itemId = o.getInt("item_id");

                               //and then check if itemId equals 2 or not.
                               if (number == 2) {
                               String quote = hit.getString("Quote");
                               mExampleList.add(new ExampleItem(quote));
                             }
                           }

                           mExampleAdapter = new ExampleAdapter(MainActivity.this, mExampleList);
                           mRecyclerView.setAdapter(mExampleAdapter);
                           mExampleAdapter.setOnItemClickListener(MainActivity.this);

                       } catch (JSONException e) {
                           e.printStackTrace();
                       }
                   }
               }, new Response.ErrorListener() {
           @Override
           public void onErrorResponse(VolleyError error) {
               error.printStackTrace();
           }
       });

       mRequestQueue.add(request);
   }

You can use a javascript filter id.... let myId = 2; let subSet = jsonArray.filter(x => x.id == myId); Then you would write code that will send the subSet to the bin.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM