使用 Android 改造解析动态键 JSON 数组
Posted
技术标签:
【中文标题】使用 Android 改造解析动态键 JSON 数组【英文标题】:Parsing a dynamic key JSON array using Android retrofit 【发布时间】: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
...
【问题讨论】:
【参考方案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 中序列化你的响应以上是关于使用 Android 改造解析动态键 JSON 数组的主要内容,如果未能解决你的问题,请参考以下文章