Parse json with struct, error passing to array - Swift 4.0

Asked

Viewed 59 times

1

I have an error with Swift 4.0 in parse Json, I am using struct Decodable to receive json, I am new in Swift I work with objective-c.

struct dataInativa: Decodable {
    let dia_data:String
}

fileprivate func loadingDataInvalidas() {
    let urlString = "http..."
    guard let url = URL(string: urlString) else { return }
    URLSession.shared.dataTask(with: url) { (data, _, err) in
        DispatchQueue.main.async {
            if let err = err {
                print("Erro na url:", err)
                   return
            }
            guard let data = data else { return }
            do {
                let decoder = JSONDecoder()
                let datasInativas = try decoder.decode(dataInativa.self, from: data)

                print("Valores: ", datasInativas.dia_data)

            } catch let jsonErro {
                print("Erro no Json:", jsonErro)
            }
        }
    }.resume()
}

I need to pass to the array a list of dates as in the example below:

self.somedays = ["2019/05/01","2019/05/02","2019/05/03","2019/05/04"]

The error presented:

typeMismatch(Swift.Dictionary, Swift.DecodingError.Context(codingPath: [], debugDescription: "Expected to Decode Dictionary but found an array Instead." , underlyingError: nil))

Someone could help out.

1 answer

3


I would need to see JSON but by the way you want the result should be a Array.

On the line where it’s written:

let datasInativas = try decoder.decode(dataInativa.self, from: data)

Replace with:

let datasInativas = try decoder.decode(Array<dataInativa>.self, from: data)
  • 1

    Thank you very much, miss that. abs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.