【问题标题】:ActionCable answer parseActionCable 答案解析
【发布时间】:2020-12-15 06:59:50
【问题描述】:

我制作带有聊天功能的 iOS 应用。它建立在 ActionCable 之上。我使用ActionCableClient 库来处理它。一切都很好。解析收到的消息的唯一问题。 它的类型为 Any

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";
})

并且将 Any 类型转换为 Data 不起作用。我不能通过它JSONDecode。 我可以从中取出 String

String(describing: data)

但我不知道如何使用它了。如何从中获得数据模型?

【问题讨论】:

  • 这是一本字典。你可以投那个as? [String: Any]。如果你想要一个 JSONDecoder,你可以将它处理回 Data,但也许 lib 可以检索它。

标签: ios json swift parsing websocket


【解决方案1】:

这是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
        ...
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-08
    • 2014-06-01
    相关资源
    最近更新 更多