【问题标题】:Parsing a dynamic key JSON array using Android retrofit使用 Android 改造解析动态键 JSON 数组
【发布时间】:2021-09-06 14:17:31
【问题描述】:

如何使用 Android 改造来使用这个 JSON?

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

预期的输出应该在嵌套的回收器视图中:

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

【问题讨论】:

    标签: android json parsing retrofit


    【解决方案1】:

    试试下面的代码。

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

    【讨论】:

    • 产品也是动态的API
    • 那么你应该采用第一种方法,直接在 hasmap 中序列化你的响应
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-11
    • 2019-03-12
    • 2017-07-07
    • 1970-01-01
    • 2016-04-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多