Nested JsonArray parsing for Pinned ListView

146 Views Asked by At

enter image description hereI'm using this library to make a pinned section listview. My API response is below. I need to parse the nested jsonarray but the problem is I'm getting the last object only inside the second loop for JSONArray "products" such that I'm getting same 2 list row item for the first section header instead of 2 different list row item . How to parse the nested jsonarray and add it to model class?

{
  "all_cart_products": [
    {
      "seller_id": "3",
      "seller_name": "Avik Roy",
      "email": "[email protected]",
      "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": "[email protected]",
      "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));
    }

2

There are 2 best solutions below

0
On

You can easily parse this JSON using three model objects given below

AllCartProduct class

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

}

Example class

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

}

Product class

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

}

Then using the GSON library you can parse it to the model object

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

Add this dependancy

compile 'com.google.code.gson:gson:2.8.0'

and use this parser class.

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