【问题标题】:Nested JsonArray parsing for Pinned ListView固定 ListView 的嵌套 JsonArray 解析
【发布时间】:2017-09-02 14:16:33
【问题描述】:

我正在使用这个library 来制作固定部分列表视图。我的 API 响应如下。我需要解析嵌套的 jsonarray,但问题是我只在 JSONArray“产品”的第二个循环内获取最后一个对象,这样我就为第一节标题获得了相同的 2 个列表行项目,而不是 2 个不同的列表行物品 。如何解析嵌套的 jsonarray 并将其添加到模型类中?

{
  "all_cart_products": [
    {
      "seller_id": "3",
      "seller_name": "Avik Roy",
      "email": "nits.avik@gmail.com",
      "seller_image": "http://104.131.83.218/makeoffer/upload/userimage/1491225073_ajeet_1000016806.jpg",
      "products": [
        {
          "id": "7",
          "product_user_id": "3",
          "name": "rtutyikuyliou",
          "desc": "Ytuykloiu sadfvdsbhdf fvdn dfjntgfkmhygdd dfsdhbgdf asfsedgdrjn sfvdsbhdf sfaswg adaswfg ADXAV adcasvfs adaswfsde safds",
          "quantity": "1",
          "unit_price": "100.00",
          "total_price1": 100,
          "total_price": "100.00",
          "itemImage": "http://104.131.83.218/makeoffer/upload/product/1489739799Manab.jpg",
          "totalquantity": "48"
        },
        {
          "id": "1",
          "product_user_id": "3",
          "name": "product1",
          "desc": "Ewfdewfs dvdfsovdfjudf bvdfofidksopdfb dfbldfjbldfb fdbdfkljbdfb dfbfkdjbdfb dfbdfjklbdfb dfbldfjkdf bdflkbjdfbdf bdfkljbdfb dfbldfkjbdf bdfbldfjkbdf bdfklbjdfdf bdfbjdflbdf bdf",
          "quantity": "1",
          "unit_price": "200.00",
          "total_price1": 200,
          "total_price": "200.00",
          "itemImage": "http://104.131.83.218/makeoffer/upload/product/1489737382Manab.jpg",
          "totalquantity": "50"
        }
      ]
    },
    {
      "seller_id": "11",
      "seller_name": "Kartik  roy",
      "email": "nits.kartik@gmail.com",
      "seller_image": "http://104.131.83.218/makeoffer/upload/userimage/14902548541490254849295.jpg",
      "products": [
        {
          "id": "12",
          "product_user_id": "11",
          "name": "Titli ghh\n",
          "desc": "uh ghd Ff hg hi JJ jf TD ghh",
          "quantity": "1",
          "unit_price": "10.00",
          "total_price1": 10,
          "total_price": "10.00",
          "itemImage": "http://104.131.83.218/makeoffer/upload/product/1490254269myprod.jpg",
          "totalquantity": "5"
        }
      ]
    }
  ],
  "total_qty": 1,
  "Ack": 1
}
private void prepareData(){
        if(arrayList!=null )arrayList.clear();
        StringRequest stringRequest = new StringRequest(Request.Method.POST, "http://www.example.com/webservice/getAllCartProducts",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        String childimage="", childtitle="", childqty="", childprice="";
                        System.out.println("sammy_response "+response);
                        try {
                            JSONObject jObj = new JSONObject(response);
                            if(jObj.getInt("Ack")==1){
                                JSONArray jsonArray = jObj.getJSONArray("all_cart_products");
                                for(int i=0;i<jsonArray.length();i++){
                                    JSONObject main = jsonArray.getJSONObject(i);
                                    model = new Model();                                        model.setHeaderimage(main.getString("seller_image"));                                       model.setHeadertext(main.getString("seller_name"));                                       model.setHeaderid(main.getString("seller_id"));
                                    JSONArray jarr = main.getJSONArray("products");
                                    for(int j=0; j<jarr.length(); j++){
                                        JSONObject obj = jarr.getJSONObject(j);
                                        /*childimage = obj.getString("itemImage");
                                        childtitle = obj.getString("name");
                                        childqty = obj.getString("quantity");
                                        childprice = obj.getString("total_price");*/                                           model.setChildimage(obj.getString("itemImage"));                                          model.setChildtitle(obj.getString("name"));                                           model.setChildqty(obj.getString("quantity"));                                           model.setChildprice(obj.getString("total_price"));

                                        arrayList.add(model);
                                    }
                                   /* model.setChildimage(childimage);
                                    model.setChildtitle(childtitle);
                                    model.setChildqty(childqty);
                                    model.setChildprice(childprice);*/
                                }
                            }
                            mAdapter.notifyDataSetChanged();
                        } catch (JSONException e) {
                            // JSON error
                            System.out.println("sammy_JSONError "+e);
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                if (error instanceof TimeoutError) {  
                 Toast.makeText(MainActivity.this,getString(R.string.tooslow),Toast.LENGTH_LONG).show();
                }else if (error instanceof NoConnectionError){
                    Toast.makeText(MainActivity.this,getString(R.string.nointernet),Toast.LENGTH_LONG).show();
                }else if (error instanceof AuthFailureError) {
                    System.out.println("sammy_AuthFailureError "+error);
                } else if (error instanceof ServerError) {
                    System.out.println("sammy_ServerError "+error);
                } else if (error instanceof NetworkError) {
                    System.out.println("sammy_NetworkError "+error);
                } else if (error instanceof ParseError) {
                    System.out.println("sammy_ParseError "+error);
                }
            }
        }) {
            @Override
            protected Map<String, String> getParams() {
                Map<String, String> params = new HashMap<String, String>();
                params.put("user_id", "7");
                return params;
            }
        };

        RequestQueue requestQueue = Volley.newRequestQueue(MainActivity.this);
        requestQueue.add(stringRequest);
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(
                10000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
                DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
    }

【问题讨论】:

  • 问题不清楚?
  • 您是否要求该 JSON 的解析器?
  • 我得到了每个标题的重复子对象,即products jsonarray 中的最后一个 jsonobject 在 j-for 循环中被覆盖。请检查图片。
  • 我只是想知道在解析子jsonarray时我做错了什么。
  • 发布你的模态类

标签: android pinned-header-list-view


【解决方案1】:

您可以使用下面给出的三个模型对象轻松解析此 JSON

AllCartProduct 类

public class AllCartProduct {

private String sellerId;
private String sellerName;
private String email;
private String sellerImage;
private List<Product> products = null;

public String getSellerId() {
return sellerId;
}

public void setSellerId(String sellerId) {
this.sellerId = sellerId;
}

public String getSellerName() {
return sellerName;
}

public void setSellerName(String sellerName) {
this.sellerName = sellerName;
}

public String getEmail() {
return email;
}

public void setEmail(String email) {
this.email = email;
}

public String getSellerImage() {
return sellerImage;
}

public void setSellerImage(String sellerImage) {
this.sellerImage = sellerImage;
}

public List<Product> getProducts() {
return products;
}

public void setProducts(List<Product> products) {
this.products = products;
}

}

示例类

public class Example {

private List<AllCartProduct> allCartProducts = null;
private Integer totalQty;
private Integer ack;

public List<AllCartProduct> getAllCartProducts() {
return allCartProducts;
}

public void setAllCartProducts(List<AllCartProduct> allCartProducts) {
this.allCartProducts = allCartProducts;
}

public Integer getTotalQty() {
return totalQty;
}

public void setTotalQty(Integer totalQty) {
this.totalQty = totalQty;
}

public Integer getAck() {
return ack;
}

public void setAck(Integer ack) {
this.ack = ack;
}

}

产品类别

public class Product {

private String id;
private String productUserId;
private String name;
private String desc;
private String quantity;
private String unitPrice;
private Integer totalPrice1;
private String totalPrice;
private String itemImage;
private String totalquantity;

public String getId() {
return id;
}

public void setId(String id) {
this.id = id;
}

public String getProductUserId() {
return productUserId;
}

public void setProductUserId(String productUserId) {
this.productUserId = productUserId;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getDesc() {
return desc;
}

public void setDesc(String desc) {
this.desc = desc;
}

public String getQuantity() {
return quantity;
}

public void setQuantity(String quantity) {
this.quantity = quantity;
}

public String getUnitPrice() {
return unitPrice;
}

public void setUnitPrice(String unitPrice) {
this.unitPrice = unitPrice;
}

public Integer getTotalPrice1() {
return totalPrice1;
}

public void setTotalPrice1(Integer totalPrice1) {
this.totalPrice1 = totalPrice1;
}

public String getTotalPrice() {
return totalPrice;
}

public void setTotalPrice(String totalPrice) {
this.totalPrice = totalPrice;
}

public String getItemImage() {
return itemImage;
}

public void setItemImage(String itemImage) {
this.itemImage = itemImage;
}

public String getTotalquantity() {
return totalquantity;
}

public void setTotalquantity(String totalquantity) {
this.totalquantity = totalquantity;
}

}

然后使用 GSON 库可以将其解析为模型对象

 Gson gson = new Gson();
           Example modelObject =  (Example) gson.fromJson(response, Example.class);

【讨论】:

    【解决方案2】:

    添加这个依赖

    编译'com.google.code.gson:gson:2.8.0'

    并使用这个解析器类。

     public class MyParserclass {
    
    @com.google.gson.annotations.SerializedName("all_cart_products")
    public List<AllCartProducts> allCartProducts;
    @com.google.gson.annotations.SerializedName("total_qty")
    public int totalQty;
    @com.google.gson.annotations.SerializedName("Ack")
    public int ack;
    
    public static class Products {
        @com.google.gson.annotations.SerializedName("id")
        public String id;
        @com.google.gson.annotations.SerializedName("product_user_id")
        public String productUserId;
        @com.google.gson.annotations.SerializedName("name")
        public String name;
        @com.google.gson.annotations.SerializedName("desc")
        public String desc;
        @com.google.gson.annotations.SerializedName("quantity")
        public String quantity;
        @com.google.gson.annotations.SerializedName("unit_price")
        public String unitPrice;
        @com.google.gson.annotations.SerializedName("total_price1")
        public int totalPrice1;
        @com.google.gson.annotations.SerializedName("total_price")
        public String totalPrice;
        @com.google.gson.annotations.SerializedName("itemImage")
        public String itemimage;
        @com.google.gson.annotations.SerializedName("totalquantity")
        public String totalquantity;
    
        public String getId() {
            return id;
        }
    
        public void setId(String id) {
            this.id = id;
        }
    
        public String getProductUserId() {
            return productUserId;
        }
    
        public void setProductUserId(String productUserId) {
            this.productUserId = productUserId;
        }
    
        public String getName() {
            return name;
        }
    
        public void setName(String name) {
            this.name = name;
        }
    
        public String getDesc() {
            return desc;
        }
    
        public void setDesc(String desc) {
            this.desc = desc;
        }
    
        public String getQuantity() {
            return quantity;
        }
    
        public void setQuantity(String quantity) {
            this.quantity = quantity;
        }
    
        public String getUnitPrice() {
            return unitPrice;
        }
    
        public void setUnitPrice(String unitPrice) {
            this.unitPrice = unitPrice;
        }
    
        public int getTotalPrice1() {
            return totalPrice1;
        }
    
        public void setTotalPrice1(int totalPrice1) {
            this.totalPrice1 = totalPrice1;
        }
    
        public String getTotalPrice() {
            return totalPrice;
        }
    
        public void setTotalPrice(String totalPrice) {
            this.totalPrice = totalPrice;
        }
    
        public String getItemimage() {
            return itemimage;
        }
    
        public void setItemimage(String itemimage) {
            this.itemimage = itemimage;
        }
    
        public String getTotalquantity() {
            return totalquantity;
        }
    
        public void setTotalquantity(String totalquantity) {
            this.totalquantity = totalquantity;
        }
    }
    
    public static class AllCartProducts {
        @com.google.gson.annotations.SerializedName("seller_id")
        public String sellerId;
        @com.google.gson.annotations.SerializedName("seller_name")
        public String sellerName;
        @com.google.gson.annotations.SerializedName("email")
        public String email;
        @com.google.gson.annotations.SerializedName("seller_image")
        public String sellerImage;
        @com.google.gson.annotations.SerializedName("products")
        public List<Products> products;
    
        public String getSellerId() {
            return sellerId;
        }
    
        public void setSellerId(String sellerId) {
            this.sellerId = sellerId;
        }
    
        public String getSellerName() {
            return sellerName;
        }
    
        public void setSellerName(String sellerName) {
            this.sellerName = sellerName;
        }
    
        public String getEmail() {
            return email;
        }
    
        public void setEmail(String email) {
            this.email = email;
        }
    
        public String getSellerImage() {
            return sellerImage;
        }
    
        public void setSellerImage(String sellerImage) {
            this.sellerImage = sellerImage;
        }
    
        public List<Products> getProducts() {
            return products;
        }
    
        public void setProducts(List<Products> products) {
            this.products = products;
        }
    }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-09-22
      • 2023-04-08
      • 2015-09-12
      • 2015-02-22
      • 2017-05-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-17
      相关资源
      最近更新 更多