liusuyi
2025-02-20 ab55c60112c72fcfe7836a91a278f316cddd7c00
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.ard.tianyu.websocket.utils;
 
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.TypeReference;
import com.ard.tianyu.websocket.domain.WsMessage;
 
public class WsMessageConverter {
 
    // 将 JSON 字符串转换为 WsMessage 对象
    public static  <T> WsMessage<T> fromJson(String json, Class<T> payloadType) {
        // 使用 TypeReference 来处理泛型
        return JSON.parseObject(json, new TypeReference<WsMessage<T>>(){});
    }
 
    // 将 WsMessage 对象转换为 JSON 字符串
    public static <T> String toJson(WsMessage<T> wsMessage) {
        return JSON.toJSONString(wsMessage);
    }
}