【问题标题】:How to convert dictionaries into an an array to populate table view如何将字典转换为数组以填充表格视图
【发布时间】:2021-10-19 21:01:33
【问题描述】:

我正在尝试将从此返回的字典转换为来自 Message 结构的数组以填充表格视图。在这样做的过程中,我遇到了一个错误,显示为

"keyNotFound(CodingKeys(stringValue: "messages", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with"

我该如何解决这个问题?请看下面的代码:

  struct MessageResponse: Codable {
        let messages: [Message]
    }
    
    struct Message:Codable {
        
        var userID: String
        var username: String
        var avatarURL: String
        var text: String
        var messages:[String] = []
       
        enum CodingKeys: String, CodingKey {
            case userID = "user_id"
            case username = "name"
            case avatarURL = "avatar_url"
            case messages = "message"
        }
        
        init(from decoder: Decoder) throws {
            let values = try decoder.container(keyedBy: CodingKeys.self)
            userID = try values.decodeIfPresent(String.self, forKey: .userID) ?? ""
            username = try values.decodeIfPresent(String.self, forKey: .username) ?? ""
            avatarURL = try values.decodeIfPresent(String.self, forKey: .avatarURL) ?? ""
            text = try values.decodeIfPresent(String.self, forKey: .messages) ?? ""
           
            for message in messages{
                let chatInfo =  try values.decodeIfPresent(String.self, forKey: Message.CodingKeys(rawValue:message)!)
                messages.append(chatInfo ?? "")
            }
   

func getChat(){
        ChatClient.shared.getMessages {  messageResponse in
            print(self.messages = messageResponse.messages)
        }
        
    }        }
           

这是我要解码的 JSON

{ "data" : [ { "user_id" : "1", "name" : "Drew", "avatar_url" : "http://dev.rapptrlabs.com/Tests/images/drew_avatar.png", "message" : "Team, can we give job applicants taking this test some examples of the types of apps they’d be working on if they joined our team?" }, { "user_id" : "2", "name" : "Abby", "avatar_url" : "http://dev.rapptrlabs.com/Tests/images/abby_avatar.png", "message" : "We work on ecommerce apps for brands like PromGirl & Simply Dresses." }, { "user_id" : "3", "name" : "Taylor", "avatar_url" : "http://dev.rapptrlabs.com/Tests/images/taylor_avatar.png", "message" : "You know those scooter sharing services that have been popping up? We developed and support one of those: Movo." }, { "user_id" : "2", "name" : "Abby", "avatar_url" : "http://dev.rapptrlabs.com/Tests/images/abby_avatar.png", "message" : "We do a lot of hardware-pairing apps as well like Conair’s Smart WeightWatchers Scale and Phlex’s new smart goggles." } ] }

【问题讨论】:

  • 将字典转换成数组是什么意思? (不是我的语法错误)
  • 如果有人说“我遇到了一个错误”,你说什么?在哪里!?在哪一行?
  • 供您参考,您的“数据”人是一个字典数组。
  • 您好,它不是一个数组。最初,当我尝试解析它时,显示的错误是“预期解析数组但找到了字典”
  • 为什么需要自定义解码器?尝试不使用它。

标签: ios json swift


【解决方案1】:

无需创建自定义解码器。除此之外,您的主要问题是您的 MessageResponse messages 属性键应该是“数据”


// MARK: - MessageResponse
struct MessageResponse: Codable {
    let messages: [Message]
    enum CodingKeys: String, CodingKey {
        case messages = "data"
    }
}

// MARK: - Message
struct Message: Codable {
    let userID, name: String
    let avatarURL: String
    let message: String
    enum CodingKeys: String, CodingKey {
        case userID = "user_id", name, avatarURL = "avatar_url", message
    }
}

游乐场测试:

let json = """
{ "data" : [ { "user_id" : "1", "name" : "Drew", "avatar_url" : "http://dev.rapptrlabs.com/Tests/images/drew_avatar.png", "message" : "Team, can we give job applicants taking this test some examples of the types of apps they’d be working on if they joined our team?" }, { "user_id" : "2", "name" : "Abby", "avatar_url" : "http://dev.rapptrlabs.com/Tests/images/abby_avatar.png", "message" : "We work on ecommerce apps for brands like PromGirl & Simply Dresses." }, { "user_id" : "3", "name" : "Taylor", "avatar_url" : "http://dev.rapptrlabs.com/Tests/images/taylor_avatar.png", "message" : "You know those scooter sharing services that have been popping up? We developed and support one of those: Movo." }, { "user_id" : "2", "name" : "Abby", "avatar_url" : "http://dev.rapptrlabs.com/Tests/images/abby_avatar.png", "message" : "We do a lot of hardware-pairing apps as well like Conair’s Smart WeightWatchers Scale and Phlex’s new smart goggles." } ] }
"""

do {
    let response = try JSONDecoder().decode(MessageResponse.self, from: Data(json.utf8))
    print(response)
} catch {
    print(error)
}

这将打印:

MessageResponse(messages: [__lldb_expr_9.Message(userID: "1", name: "Drew", avatarURL: "http://dev.rapptrlabs.com/Tests/images/drew_avatar.png", message: "Team , 我们能否给参加此测试的求职者一些示例,说明他们加入我们团队后将使用的应用程序类型?"), __lldb_expr_9.Message(userID: "2", name: "Abby", avatarURL: " http://dev.rapptrlabs.com/Tests/images/abby_avatar.png", message: "我们为 PromGirl & Simply Dresses 等品牌开发电子商务应用程序。"), __lldb_expr_9.Message(userID: "3", name: "Taylor", avatarURL: "http://dev.rapptrlabs.com/Tests/images/taylor_avatar.png", message: "你知道那些已经出现的滑板车共享服务吗?我们开发并支持其中之一:Movo ."), __lldb_expr_9.Message(userID: "2", name: "Abby", avatarURL: "http://dev.rapptrlabs.com/Tests/images/abby_avatar.png", message: "我们做了很多硬件配对应用程序以及 Conair 的 Smart WeightWatchers Scale 和 Phlex 的新型智能护目镜。")])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-07-22
    • 1970-01-01
    • 2015-09-22
    • 1970-01-01
    • 2015-12-05
    • 1970-01-01
    • 2014-02-03
    • 1970-01-01
    相关资源
    最近更新 更多