我该如何在Android kotlin,Moshi和Retrofit中解析具有嵌套动态键的JSON?
我从alpha-vantage获取了这个JSON。
格式示例:
{
"Meta Data": {
"1. Information": "Intraday (15min) open, high, low, close prices and volume",
"2. Symbol": "AAME",
"3. Last Refreshed": "2019-11-18 16:00:00",
"4. Interval": "15min",
"5. Output Size": "Compact",
"6. Time Zone": "US/Eastern"
},
"Time Series (15min)": {//Dynamic - > Time Series (5min) / Time Series (30min)
"2019-11-18 16:00:00": {//Dynamic
"1. open": "1.6700",
"2. high": "1.6700",
"3. low": "1.5700",
"4. close": "1.5700",
"5. volume": "1521"
},
"2019-11-18 15:45:00": {//Dynamic
"1. open": "1.6600",
"2. high": "1.7400",
"3. low": "1.6600",
"4. close": "1.7400",
"5. volume": "355"
}
}
}
我试过使用自定义适配器,但是我无法找到一种方法来解析双重嵌套的动态键。
目前我使用手动解析:
fun convertJsonToItemDetails(jso: JSONObject) {
val meta: JSONObject? = jso.optJSONObject("Meta Data")
var metaData: ItemMetaData? = null
meta?.apply {
val information = optString("1. Information")
val symbol = optString("2. Symbol")
val lastRefreshed = optString("3. Last Refreshed")
val interval = optString("4. Interval")
val outputSize = optString("5. Output Size")
val timeZone = optString("6. Time Zone")
metaData =
ItemMetaData(information, symbol, lastRefreshed, interval, outputSize, timeZone)
}
if (metaData == null) {
//TODO return error object
return
}
val timeSeriesJSON = jso.optJSONObject("Time Series (${metaData?.interval})")
val timeSeires = HashMap<String, IntervalOutput>()
if (timeSeriesJSON == null) {
//TODO return error object
return
}
for (key in timeSeriesJSON.keys()) {
val intervalOutPutJSON = timeSeriesJSON.getJSONObject(key)
val open = intervalOutPutJSON.getString("1. open")
val high = intervalOutPutJSON.getString("2. high")
val low = intervalOutPutJSON.getString("3. low")
val close = intervalOutPutJSON.getString("4. close")
val volume = intervalOutPutJSON.getString("5. volume")
timeSeires[key] = IntervalOutput(open, high, low, close, volume)
}
val itemDetails = ItemDetails(metaData, timeSeires)
_itemDetails.value = itemDetails
}
@JsonRawValue
的东西。但它不是Moshi,因此只是一条注释;-) - longi