I'm still a beginner in Swift and in programming. And I don't have any experience with JSON. Now I tried to make a App on my own. I tried my Code first in Playgrounds but errors occured and I don't know why 😀
So first here is my Code:
import UIKit
import Foundation
struct MonsterInfo : Decodable {
var id : Int
var name: String
var type: String
var elements: [String]
var ailments: [String]?
var locations: [String]
var resistances: [String]
var weaknesses: [String]
}
func getMonsterInfoAPI(id: Int) {
let url = URL(string: "https://mhw-db.com/monsters/\(id)")!
let session = URLSession.shared
let task = session.dataTask(with: url, completionHandler: {data, response, error in
do {
let json = try? JSONSerialization.jsonObject(with: data!, options: [])
// print(json)
} catch {
print("JSON error: \(error.localizedDescription)")
}
let decoder = JSONDecoder()
let temp = try! decoder.decode(MonsterInfo.self, from: data!)
print(temp.name)
print(temp.locations)
})
task.resume()
}
getMonsterInfoAPI(id: 4)The problem is: If i use print(temp.name) it works but on the other propertys I declared in the Struct it always says "
Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.typeMismatch(Swift.String, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "ailments", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "Expected to decode String but found a dictionary instead.", underlyingError: nil)): file MyPlayground.playground, line 34"
If I now change the types of the MonsterInfo ailments to dictionary like this...
struct MonsterInfo : Decodable {
var id : Int
var name: String
var type: String
var elements: [String]
var ailments: [String:Int]
var locations: [String]
var resistances: [String]
var weaknesses: [String]
}the follwing error occurs:
Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.typeMismatch(Swift.Dictionary<Swift.String, Swift.Int>, Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "ailments", intValue: nil)], debugDescription: "Expected to decode Dictionary<String, Int> but found an array instead.", underlyingError: nil)): file MyPlayground.playground, line 32
Why does this error occurs? I'm confused first it says "...but dictionary found" and then "...but found array"
How to achieve my aim to get from all "propertys" in my struct the right value even if it is null