How can I parse Nested JSON with NESTED dynamic keys in Android kotlin, Moshi and Retrofit?
I get this JSON from alpha-vantage.
Format example:
{
"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"
}
}
}
I tried to use custom adapter but I can't find a way to parse a double nested dynamic keys with it. For now I use manual parsing:
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
}