【问题标题】:how to create a pojo class with dynamic key for arrayname如何使用 arrayname 的动态键创建 pojo 类
【发布时间】:2016-09-29 08:22:16
【问题描述】:

我正在使用 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 中的各种链接,但无法解决问题。

【问题讨论】:

  • 您可以采用两种方式。实现您自己的反序列化器或告诉 Retrofit 您希望 JsonObject(GSON 库) 作为响应并从该对象获取内部数组。
  • 检查this answer
  • @Suresh Basnet :检查以下答案并完整解析您的 json 响应
  • @Suresh Basnet:完成了吗?
  • @jai 我已经复制了我的响应字符串,并且每次它显示的值都不是来自服务器的响应字符串。我们不能直接为 mCategory 设置 Name、Id 和 Category。它应该首先使用动态键设置数组。

标签: android json jsonschema2pojo


【解决方案1】:

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

    }

【讨论】:

    【解决方案2】:

    在我看来,不推荐这种格式。date 应该是 "date":"2016-10-01" 之类的值,而不是 json key

    【讨论】:

    • 这不是问题的真正答案,但它是一个该死的有效观点!键不应该是动态的
    猜你喜欢
    • 2018-12-08
    • 2011-10-30
    • 2017-12-04
    • 1970-01-01
    • 2016-08-28
    • 2019-06-09
    • 2021-08-12
    • 2023-02-08
    • 1970-01-01
    相关资源
    最近更新 更多