我制作的iOS应用程序有聊天功能。它是建立在ActionCable上的。我使用ActionCableClient库来处理它。一切都很好。解析接收到的消息时唯一的问题。它的类型为任意
Optional({
data = {
author = {
"avatar_url" = "<null>";
name = "\U0410\U043b\U043b\U0430";
uid = "eb1b5fe6-5693-4966-bf72-a30596353677";
};
"created_at" = "1598446059.511528";
file = "<null>";
image = "<null>";
quote = "<null>";
status = red;
text = "test message";
type = OperatorMessage;
uid = "30b4d5ed-639d-46fb-9be3-b254de3b1203";
};
type = "operator_message";
})并将任何类型转换为数据不起作用。我不能JSONDecode通过这个。我可以把字符串从里面拿出来。
String(describing: data)但我不知道该怎么用了。你如何从它得到一个数据模型?
发布于 2020-08-26 13:19:32
这是一个NSDictionary的打印。所以你可以:
guard let dict = that as? NSDictionary else { return }或者,以一种更迅速的方式:
guard let dict = that as? [String: Any] else { return } 例如,检索一些值:
let type = dict["type"] as? String
if let subdata = dict["data"] as? [String: Any] {
let text = subdata["text"] as? String
let kid = subdata["uid"] as? String
...
}如果要检索(NS)Data返回,可以使用JSONSerialization将其转换回,并使用JSONDecoder,但由于已经存在
Data ----(through JSONSerialization)----> Dictionary回过头来看数据
Data ----(through JSONSerialization)----> Dictionary ----(through JSONSerialization)----> Data ----(through JSONDecoder)----> CustomStruct同时,您可以在字典中添加一个CustomStruct init。
因此,如果您有一个可编码的结构:
struct Response: Codable {
let data: CustomData
let type: String
}
struct CustomData: Codable {
let uid: String
let text: String
...
}最快的办法是添加:
extension Response {
init?(dict: [String;: Any] {
guard let type = dict["type"] as? String?
let data = dict["data"] as? [String: Any] else { return nil }
self.type = type
self.data = data
}
}
extension CustomData {
init?(dict: [String;: Any] {
guard let uid = dict["did"] as? String?
let text = dict["text"] as? String else { return nil }
self.uid = uid
self.text = text
...
}
}https://stackoverflow.com/questions/63598271
复制相似问题