首页 > 解决方案 > 如何使用动态响应键解析 json

问题描述

如何在改造中解析以下 json 响应

{
  "MH46AF4149": [
    {
      "distance": 74,
      "date": "23-09-2019"
    },
    {
      "distance": 97,
      "date": "24-09-2019"
    },
    {
      "distance": 91,
      "date": "25-09-2019"
    },
    {
      "distance": 80,
      "date": "26-09-2019"
    },
    {
      "distance": 91,
      "date": "27-09-2019"
    },
    {
      "distance": 16,
      "date": "28-09-2019"
    }
  ]
}

MH46AF4149是一个dynamic value不断变化的每一个新的响应。

我正在使用带有 GsonConverterFactory 的 RetrofitClient。如何填充我的模型类。我应该使用哪个注释。@Expose 不起作用

标签: androidjsongsonretrofit2

解决方案


按照下面的代码,

JSONObject response = new JSONObject(responseString);
Iterator<?> keys = response.keys();
while( keys.hasNext() ) {
    String key = (String)keys.next();
    if ( response.get(key) instanceof JSONObject ) {
        JSONArray array = response.getJSONArray(key);
        for(int i = 0; i < array.length(); i++){
            JSONObject element = array.getJSONObject(i);
            //now use this array object to get strings
        }
    }
}

推荐阅读