如何将OkHttp WebSocket接收的Binance JSON字符串转为Data Class?
最佳实现方案:将Binance 24hrTicker JSON转换为Kotlin Data Class
一、创建匹配JSON结构的Kotlin Data Class
根据你提供的JSON字段,定义对应的数据类,注意字段类型要和JSON一致(部分价格类字段是字符串格式的数值,时间和ID类是长整型),并用序列化注解映射JSON的短键名:
Gson注解版
import com.google.gson.annotations.SerializedName data class Binance24HrTicker( @SerializedName("e") val eventType: String, @SerializedName("E") val eventTime: Long, @SerializedName("s") val symbol: String, @SerializedName("p") val priceChange: String, @SerializedName("P") val priceChangePercent: String, @SerializedName("w") val weightedAvgPrice: String, @SerializedName("x") val prevClosePrice: String, @SerializedName("c") val lastPrice: String, @SerializedName("Q") val lastQuantity: String, @SerializedName("b") val bestBidPrice: String, @SerializedName("B") val bestBidQuantity: String, @SerializedName("a") val bestAskPrice: String, @SerializedName("A") val bestAskQuantity: String, @SerializedName("o") val openPrice: String, @SerializedName("h") val highPrice: String, @SerializedName("l") val lowPrice: String, @SerializedName("v") val totalBaseVolume: String, @SerializedName("q") val totalQuoteVolume: String, @SerializedName("O") val statsOpenTime: Long, @SerializedName("C") val statsCloseTime: Long, @SerializedName("F") val firstTradeId: Long, @SerializedName("L") val lastTradeId: Long, @SerializedName("n") val totalTrades: Long )
Moshi注解版
如果使用Moshi,替换注解即可:
import com.squareup.moshi.Json data class Binance24HrTicker( @Json(name = "e") val eventType: String, @Json(name = "E") val eventTime: Long, // 其余字段定义与上面一致,仅替换注解 )
二、选择并配置JSON解析库
Kotlin生态中常用的JSON解析库有Gson和Moshi,二选一即可:
1. Gson配置
在Module级别的build.gradle添加依赖:
dependencies { implementation 'com.google.code.gson:gson:2.10.1' }
2. Moshi配置
添加Moshi依赖(包含Kotlin代码生成,提升解析性能):
dependencies { implementation 'com.squareup.moshi:moshi:1.14.0' kapt 'com.squareup.moshi:moshi-kotlin-codegen:1.14.0' }
同时给Data Class添加代码生成注解:
import com.squareup.moshi.JsonClass @JsonClass(generateAdapter = true) data class Binance24HrTicker( // 字段定义 )
三、在WebSocket回调中实现解析
在onMessage方法中完成JSON到Data Class的转换,同时捕获异常避免崩溃:
Gson实现
import com.google.gson.Gson private val gson = Gson() override fun onMessage(webSocket: WebSocket, text: String) { try { val ticker = gson.fromJson(text, Binance24HrTicker::class.java) // 处理转换后的ticker对象,比如更新UI、存储数据 Log.d("Websocket", "解析成功: ${ticker.symbol} 最新价: ${ticker.lastPrice}") } catch (e: Exception) { Log.e("Websocket", "JSON解析失败", e) } }
Moshi实现
import com.squareup.moshi.Moshi private val moshi = Moshi.Builder().build() private val tickerAdapter = moshi.adapter(Binance24HrTicker::class.java) override fun onMessage(webSocket: WebSocket, text: String) { try { val ticker = tickerAdapter.fromJson(text) ticker?.let { // 处理解析后的ticker对象 Log.d("Websocket", "解析成功: ${it.symbol} 最新价: ${it.lastPrice}") } ?: Log.e("Websocket", "解析结果为空") } catch (e: Exception) { Log.e("Websocket", "JSON解析失败", e) } }
四、注意事项
- 字段类型匹配:Binance返回的部分价格字段为字符串(避免浮点精度丢失),如需计算再转换为数值类型。
- 异常处理:必须捕获解析异常,防止因JSON格式变化或数据异常导致App崩溃。
- 性能优化:高频推送场景下,复用Gson/Moshi实例(不要每次回调都创建),Moshi代码生成版本性能优于反射版本。
内容的提问来源于stack exchange,提问作者Electrocode
相关产品推荐
相关产品推荐

