A decodificação JSON não funciona como esperado rapidamente 4
se eu quiser decodificar meu JSON, algo estranho está acontecendo.
Aqui estão as estruturas
struct chatMessages : Codable {
var message: [chatMessage]
}
struct chatMessage : Codable {
var user: String
var message: String
var status: String
var latitude: Double
var longitude: Double
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
user = try values.decode(String.self, forKey: .user)
message = try values.decode(String.self, forKey: .message)
status = try values.decode(String.self, forKey: .status)
latitude = try values.decodeIfPresent(Double.self, forKey: .latitude) ?? 0.0
longitude = try values.decodeIfPresent(Double.self, forKey: .longitude) ?? 0.0
}
}
E aqui a função
func loadChats() {
print("Try to load chats...")
do {
let jsonData = W.getDataAsData(chatURL)
print(jsonData)
print(String.init(data: jsonData, encoding: .utf8)!)
print("-----------")
let jsonDecoder = JSONDecoder()
let chatMessage1 = try jsonDecoder.decode(chatMessage.self, from: jsonData)
print(chatMessage1)
}
catch {
print("Something went wrong")
print("\(error)")
}
}
se o JSON retornado for{"user":"test","message":"Hello welcome","status":"admin","latitude":0,"longitude":0}
.
está voltandochatMessage(user: "test", message: "Hello welcome", status: "admin", latitude: 0.0, longitude: 0.0)
mas se houver mais mensagens, por exemplo[{"user":"user1","message":"Hello welcome","status":"admin","latitude":0,"longitude":0},{"user":"user2","message":"Hello welcome","status":"admin","latitude":0,"longitude":0}]
Não consigo fazer funcionar. Está voltandotypeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))
Eu tentei comchatMessages.self
mas isso não foi como o esperado. O que estou fazendo errado?
Desde já, obrigado.