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>>() {}.typeval 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>>() {}.typeGson().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>>() {}.typeGson().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` 是否为 200if (webSocketBaseBean.code != 200) {return}// 回调是否初始化if (mListener == null) {return}when (webSocketBaseBean.data) {is Data -> {val updateInfo = webSocketBaseBean.data as DatamListener!!.downloadData(updateInfo)}is String -> {when (webSocketBaseBean.type) {}val downloadUrl = webSocketBaseBean.data as StringXLog.e("------downloadUrl----$downloadUrl")mListener!!.defaultRefresh()}else -> {XLog.e("解析的data---${webSocketBaseBean.data}")}}} catch (e: Exception) {XLog.e("解析异常: ${e.message}")}}