1. 创建解析类
class WebSocketParserChain {
private val parsers = mutableListOf<WebSocketDataParser>()
fun addParser(parser: WebSocketDataParser): WebSocketParserChain {
parsers.add(parser)
return this
}
fun parse(text: String): WebSocketResponseBaseBean<*>? {
for (parser in parsers) {
val result = parser.parse(text)
if (result != null) {
return result
}
}
return null
}
}
/**
* 解析的接口
*/
interface WebSocketDataParser {
fun parse(text: String): WebSocketResponseBaseBean<*>?
}
/**
* 对象解析
*/
class DataParser : WebSocketDataParser {
override fun parse(text: String): WebSocketResponseBaseBean<*>? {
return try {
val objectType = object : TypeToken<WebSocketResponseBaseBean<Data>>() {}.type
val webSocketBaseBean: WebSocketResponseBaseBean<*> = Gson().fromJson(text, objectType)
// 如果解析后的 data 是对象(Data),直接返回结果
if (webSocketBaseBean.data != null && webSocketBaseBean.data is Data) {
webSocketBaseBean
} else {
XLog.e("DataParser----json解析对应的bean---${webSocketBaseBean.data}")
null // 如果 data 不是对象,返回 null 传递给下一个解析器
}
} catch (e: JsonSyntaxException) {
XLog.e("DataParser----json解析异常---${e.message}")
null // 如果解析失败,返回 null
}
}
}
/**
* string 解析
*/
class StringParser: WebSocketDataParser {
override fun parse(text: String): WebSocketResponseBaseBean<*>? {
return try {
val stringType = object : TypeToken<WebSocketResponseBaseBean<String>>() {}.type
Gson().fromJson(text, stringType)
} catch (e: JsonSyntaxException) {
XLog.e("StringParser-----json异常---${e.message}")
null
}
}
}
/**
* object 解析 默认解析 添加一个兜底方案 避免返回的data 既不是字符串 又不是对象
*/
class ObjectParser: WebSocketDataParser {
override fun parse(text: String): WebSocketResponseBaseBean<*>? {
return try {
val stringType = object : TypeToken<WebSocketResponseBaseBean<Any>>() {}.type
Gson().fromJson(text, stringType)
} catch (e: JsonSyntaxException) {
XLog.e("ObjectParser-----json异常---${e.message}")
null
}
}
}
2.使用方法
override fun onMessage(text: String) {
XLog.e("onMessage----text---$text")
try {
val parserChain = WebSocketParserChain()
.addParser(DataParser()) // 尝试解析为对象类型
.addParser(StringParser()) // 如果失败则尝试解析为字符串类型
.addParser(ObjectParser()) // 如果失败则尝试解析为Any类型 兜底方案
val webSocketBaseBean = parserChain.parse(text)
XLog.e("当前websocket数据为--$webSocketBaseBean------mListener---$mListener")
if (webSocketBaseBean==null) {
return
}
// 判断 `code` 是否为 200
if (webSocketBaseBean.code != 200) {
return
}
// 回调是否初始化
if (mListener == null) {
return
}
when (webSocketBaseBean.data) {
is Data -> {
val updateInfo = webSocketBaseBean.data as Data
mListener!!.downloadData(updateInfo)
}
is String -> {
when (webSocketBaseBean.type) {
}
val downloadUrl = webSocketBaseBean.data as String
XLog.e("------downloadUrl----$downloadUrl")
mListener!!.defaultRefresh()
}
else -> {
XLog.e("解析的data---${webSocketBaseBean.data}")
}
}
} catch (e: Exception) {
XLog.e("解析异常: ${e.message}")
}
}