【发布时间】: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." } ] }
【问题讨论】:
-
将字典转换成数组是什么意思? (不是我的语法错误)
-
如果有人说“我遇到了一个错误”,你说什么?在哪里!?在哪一行?
-
供您参考,您的“数据”人是一个字典数组。
-
您好,它不是一个数组。最初,当我尝试解析它时,显示的错误是“预期解析数组但找到了字典”
-
为什么需要自定义解码器?尝试不使用它。