Reputation: 15
I'm new to Codable and been playing around it today.
My current JSON model look like this:
{
"status": 200,
"code": 200,
"message": {
"1dHZga0QV5ctO6yhHUhy": {
"id": "23",
"university_location": "Washington_DC",
"docID": "1dHZga0QV5ctO6yhHUhy"
},
"0dbCMP7TrTEnpRbEleps": {
"id": "22",
"university_location": "Timber Trails, Nevada",
"docID": "0dbCMP7TrTEnpRbEleps"
}
}
}
However, Trying to decode this response with:
struct USA: Codable
{
//String, URL, Bool and Date conform to Codable.
var status: Int
var code: Int
// Message Data
var message: Array<String>
}
Gives out:
Expected to decode Array but found a dictionary instead.
Updating the message
to Dictionary<String,String
produces:
typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "message", intValue: nil), _JSONKey(stringValue: "1dHZga0QV5ctO6yhHUhy", intValue: nil)], debugDescription: "Expected to decode String but found a dictionary instead.", underlyingError: nil))
Upvotes: 0
Views: 2381
Reputation: 100503
message
key is a dictionary not an array
struct Root: Codable {
let status, code: Int
let message: [String: Message]
}
struct Message: Codable {
let id, universityLocation, docID: String
}
do {
let dec = JSONDecoder()
dec.keyDecodingStrategy = .convertFromSnakeCase
let res = try dec.decode(Root.self, from: data)
}
catch{
print(error)
}
Upvotes: 2