简体   繁体   中英

Parsing a dynamic key JSON array using Android retrofit

How to consume this JSON using Android retrofit?

{
"Pepsico": {
    "items": [
        {
            "pro_name": "Lays indian mGic masala",
            "pro_price": "0"
        },
        {
            "pro_name": "amla hair amla",
            "pro_price": "0"
        }
    ]
},
"Amul": {
    "items": [
        {
            "pro_name": "Amul butter",
            "pro_price": "48"
        },
        {
            "pro_name": "Amul cow ghee",
            "pro_price": "270"
        },
        {
            "pro_name": "Amul Kool Elaine flavored milk",
            "pro_price": "20"
        },
        {
            "pro_name": "Amul plain cheese slices",
            "pro_price": "122"
        },
        {
            "pro_name": "pure ghee",
            "pro_price": "0"
        }
    ]
}

The expected output should be in a nested recycler view:

Category Name 1
Product1
Product2
Product3
Category Name 2
Product4
Product5
Product6
...

Try with the following code.

//if your product(Pepsico,Amul...etc) is also dynamic than you can parse you api response in hashmap dynamically
 HashMap<String,Product>()

//if your product is fixed then you should use this approach
class ApiResult{
Product Pepsico;
Product Amul;

public Product getPepsico() {
    return Pepsico;
}

public void setPepsico(Product pepsico) {
    Pepsico = pepsico;
}

public Product getAmul() {
    return Amul;
}

public void setAmul(Product amul) {
    Amul = amul;
}
}


class  Product{
ArrayList<HashMap<String,String>> items;

public ArrayList<HashMap<String, String>> getItems() {
    return items;
}

public void setItems(ArrayList<HashMap<String, String>> items) {
    this.items = items;
}
} 

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