【问题标题】:How to filter json objects from an array by ID and pass to recyclerview如何按ID从数组中过滤json对象并传递给recyclerview
【发布时间】:2019-11-11 05:00:12
【问题描述】:

我有一个类似于下面给出的 json 结构的 json 文件,现在我想要所有 item_id=2 的对象并将它们传递给 recyclerview。有人可以解决我的问题吗?提前致谢

我的json文件结构是这样的

{
"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"
}
]}

【问题讨论】:

    标签: javascript android json


    【解决方案1】:
    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);
       }
    

    【讨论】:

    • 非常感谢@Nicat
    【解决方案2】:

    您可以使用 javascript 过滤器 id.... 让我的 ID = 2; 让 subSet = jsonArray.filter(x => x.id == myId); 然后您将编写将子集发送到 bin 的代码。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-10-30
      • 2021-06-04
      • 2020-03-13
      • 2015-07-20
      • 2020-03-06
      相关资源
      最近更新 更多