如何使用数组名的动态键创建一个 pojo class

how to create a pojo class with dynamic key for arrayname

我正在使用 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 个带有日期键的数组。但是这些数组的数量各不相同。

我已经通过 Whosebug 中的各种链接,但无法解决问题。

使用 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);

    }

从我的角度来看,这种格式不是 recommended.The date 应该是 "date":"2016-10-01" 之类的值,而不是 json key