JSON Decode no funciona como se esperaba rápidamente 4
si quiero decodificar mi JSON, está sucediendo algo extraño.
Aquí están las estructuras
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
}
}
Y aquí la función
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)")
}
}
si el JSON devuelto es{"user":"test","message":"Hello welcome","status":"admin","latitude":0,"longitude":0}
.
su regresochatMessage(user: "test", message: "Hello welcome", status: "admin", latitude: 0.0, longitude: 0.0)
pero si hay más mensajes, p. @[{"user":"user1","message":"Hello welcome","status":"admin","latitude":0,"longitude":0},{"user":"user2","message":"Hello welcome","status":"admin","latitude":0,"longitude":0}]
No puedo hacer que funcione. Está regresandotypeMismatch(Swift.Dictionary<Swift.String, Any>, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Dictionary<String, Any> but found an array instead.", underlyingError: nil))
He intentado conchatMessages.self
pero eso no salió como se esperaba. ¿Qué estoy haciendo mal
Gracias por adelantado