【发布时间】:2021-09-07 04:57:28
【问题描述】:
我的套接字向客户端发送数据。我需要将响应解码为这种类型(Swift):
class Msg: Decodable {
var msg: String
}
我在客户端的套接字代码 (Swift):
socket.on("Message for me") { data, ack in
do {
guard let dict = data[0] as? [String: AnyObject] else { return }
let noti = try JSONSerialization.data(withJSONObject: dict["msg"])
let decoded = try JSONDecoder().decode(Msg.self, from: noti)
print("Message from socket: \(decoded)")
} catch let err {
print(err.localizedDescription)
}
}
我的 node js 服务器正在发送:
io.to(socket.id).emit('Message for me', {msg: `only socket: ${socket.id} can see this`});
我的客户端不断出现以下错误,经过多次尝试几种不同的方法后,我还没有弄清楚原因。
Invalid top-level type in JSON write
我尝试过使用JSONSerialization.data() 和JSONSerialization.jsonObject(),但我一直收到同样的错误。我什至检查了其他一些类似的帖子,但仍然没有。任何帮助,将不胜感激。谢谢
【问题讨论】:
-
在您的套接字代码客户端中,您能否在“do”之前添加
print("--> data: " + String(data: data, encoding: .utf8)),以尝试查看您从服务器获得的信息。 -
@workingdog 我回来了
Message for me with data: [{ msg = "only socket: ....... can see this"; }]
标签: node.js swift sockets socket.io