最后,我最终将有效负载解码为 JsonArray 并手动将其内容提供给我的数据类。
这是我的数据类:
@Serializable
data class Ticker(
var channelID : String,
var channelName : String,
var pair : String,
var ticker : TickerData,
)
@Serializable
data class TickerData(
@SerialName("a")
val ask: Ask,
@SerialName("b")
val bid: Bid,
@SerialName("c")
val close: Close,
@SerialName("h")
val volume: Volume,
@SerialName("l")
val volumeWeightedAveragePrice: VolumeWeightedAveragePrice,
@SerialName("o")
val numberOfTrades: NumberOfTrades,
@SerialName("p")
val lowPrice: LowPrice,
@SerialName("t")
val highPrice: HighPrice,
@SerialName("v")
val openPrice: OpenPrice,
)
@Serializable
data class Ask(
var price: String,
var wholeLotVolume: Int,
var lotVolume: String,
)
@Serializable
data class Bid(
var price: String,
var wholeLotVolume: Int,
var lotVolume: String,
)
@Serializable
data class Close(
var price: String,
var lotVolume: String,
)
@Serializable
data class Volume(
var today: String,
var last24Hours: String,
)
@Serializable
data class VolumeWeightedAveragePrice(
var today: String,
var last24Hours: String,
)
@Serializable
data class NumberOfTrades(
var today: String,
var last24Hours: String,
)
@Serializable
data class LowPrice(
var today: String,
var last24Hours: String,
)
@Serializable
data class HighPrice(
var today: String,
var last24Hours: String,
)
@Serializable
data class OpenPrice(
var today: String,
var last24Hours: String,
)
这是我的有效负载解析器:
class KrakenApiWebSocketPayload(val json: Json) {
fun getTicker(response:String): Ticker {
val tickerArray : JsonArray = json.decodeFromString(response)
val tickerObject : JsonObject = tickerArray[1].jsonObject
val ask : JsonArray = tickerObject.get("a")!!.jsonArray
val bid : JsonArray = tickerObject.get("b")!!.jsonArray
val close : JsonArray = tickerObject.get("c")!!.jsonArray
val volume : JsonArray = tickerObject.get("h")!!.jsonArray
val volumeWeightedAveragePrice : JsonArray = tickerObject.get("l")!!.jsonArray
val numberOfTrades : JsonArray = tickerObject.get("o")!!.jsonArray
val lowPrice : JsonArray = tickerObject.get("p")!!.jsonArray
val highPrice : JsonArray = tickerObject.get("t")!!.jsonArray
val openPrice : JsonArray = tickerObject.get("v")!!.jsonArray
return Ticker(tickerArray[0].toString(),tickerArray[2].toString(),tickerArray[3].toString(),
TickerData(
Ask(ask[0].toString(),ask[1].toString().toInt(),ask[2].toString()),
Bid(bid[0].toString(),bid[1].toString().toInt(),bid[2].toString()),
Close(close[0].toString(),close[1].toString()),
Volume(volume[0].toString(),volume[1].toString()),
VolumeWeightedAveragePrice(volumeWeightedAveragePrice[0].toString(),volumeWeightedAveragePrice[1].toString()),
NumberOfTrades(numberOfTrades[0].toString(),numberOfTrades[1].toString()),
LowPrice(lowPrice[0].toString(),lowPrice[1].toString()),
HighPrice(highPrice[0].toString(),highPrice[1].toString()),
OpenPrice(openPrice[0].toString(),openPrice[1].toString())
)
)
}
}