android - 如何使用动态响应键解析 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 不起作用
解决方案
按照下面的代码,
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
}
}
}
推荐阅读
- audio - 对 500,000 个音频文件(许多重复项)进行分组的最佳方法?
- javascript - 用Javascript制作3D数组
- c# - 检测 Visual Studio 编译(对于 C++ 文件,而不是构建)开始和结束事件
- javascript - 带有 Vue 和 Vuetify 的对话框内的变量表单
- php - php:如何将 3 条数据存储在一个数组的一个位置?
- react-native - 渲染 Snackbar 会导致单元测试失败
- .net-core - .net-core 3 是否有 ssh nuget 包?
- google-apps-script - 如何在移动设备上运行应用程序脚本,一个脚本工作另一个不工作
- angular - Angular - 如何使 canActivate 等待承诺响应?
- python - 在 Python 中从 SharePoint 加载文件