我正在使用Rxandroid并进行改造。我有一个像这样动态改变数组名称的json,
{
"2016-10-02": [
{
"name": "foo",
"id": "1",
"category": "bar"
},
{
"name": "foo",
"id": "2",
"category": "bar"
},
{
"name": "foo",
"id": "3",
"category": "bar"
},
{
"name": "foo",
"id": "4",
"category": "bar"
}
],
"2016-10-01": [
{
"name": "foo",
"id": "5",
"category": "bar"
},
{
"name": "foo",
"id": "6",
"category": "bar"
},
],
"2016-10-03": [
{
"name": "foo",
"id": "5",
"category": "bar"
}
]
}
每个数组的日期键名称会自动更改,并且数组的更改次数也会更改。在此示例中,有3个带有日期键的数组。但这些阵列的数量各不相同。
我已经通过stackoverflow中的各种链接但无法解决问题。
答案 0 :(得分:1)
从我的角度来看,不建议使用此格式。date
应该是"date":"2016-10-01"
而非json key
的值。
答案 1 :(得分:0)
使用JSONObject keys()获取密钥,然后您可以迭代每个密钥以获取动态值:
JSONObject object = new JSONObject("your response string")
Iterator keys = object.keys();
//Let's consider your POJO class is CategoryClass
// Let's take HashMap to store your POJO class for specific KEY
HashMap<String, ArrayList<CategoryClass>> mMap = new HashMap<String, ArrayList<CategoryClass>>();
while(keys.hasNext()) {
// here you will get dynamic keys
String dynamicKey = (String)keys.next();
// get the value of the dynamic key
JSONArray dynamicValue = object.getJSONArray(currentDynamicKey);
//Let's store into POJO Class and Prepare HashMap.
ArrayList<CategoryClass> mCategoryList = new ArrayList<CategoryClass>();
for(int i = 0 ; i < dynamicValue.length(); i++){
CategoryClass mCategory = new CategoryClass();
mCategory.setName(dynamicValue.getString("name"));
mCategory.setId(dynamicValue.getString("id"));
mCategory.setCategory(dynamicValue.getString("category"));
mCategoryList.add(mCategory);
}
//Add Into Hashmap
mMap.put(dynamicKey, mCategoryList);
}