-2

when try a json file to decode, with the Jsondecoder().decode i get the errwor:

Thread 7: Fatal error: 'try!' expression unexpectedly raised an error: Swift.DecodingError.typeMismatch(Swift.Array, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to decode Array but found a dictionary instead.", underlyingError: nil))

what does the compiler want to tell me and where is the error in Code?

URLSession.shared.dataTask(with: url) { (dataLocation, _, _) in

    if let dataLocation = dataLocation {
        let JsonData = try! JSONDecoder().decode([LandmarkLocation].self, from: dataLocation)
        print(JsonData.count)
    }
}
.resume()

I also added the decodable protocol to the LandmarkLocation structure

burnsi
  • 6,194
  • 13
  • 17
  • 27
  • please add into question also your `LandmarkLocation` structure – Mr.SwiftOak Jun 30 '22 at 12:04
  • 1
    Likely it's `decode(LandmarkLocation.self` – vadian Jun 30 '22 at 12:04
  • You need to [edit] your question to include all relevant code (including the `LandmarkLocation` and the JSON you are trying to decode) in the form of a [mcve] in order to make the question on-topic. – Dávid Pásztor Jun 30 '22 at 12:10
  • When a throwing function fails, don't use `try!`. use something like `do { try } catch let error { // print error.description }` and actually examine the error that's thrown. – Duncan C Jun 30 '22 at 12:21
  • "Expected to decode Array but found a dictionary instead" search for this error message together with the words swift and json – Joakim Danielson Jun 30 '22 at 12:27
  • try removing the brackets from `[LandmarkLocation]` to `LandmarkLocation`. You can also put `print(String(data:dataLocation,encoding:.utf8))` right above the decoder line to actually see what the data looks like. You need to verify what you are actually getting. – lorem ipsum Jun 30 '22 at 12:28

1 Answers1

0

Try not to decode the LandmarkLocation object as an array

if let dataLocation = dataLocation {
    let JsonData = try JSONDecoder().decode(LandmarkLocation.self, from: dataLocation)
    print(JsonData.count)
}