简体   繁体   中英

Error parsing json with Swift4, imposible to print it

I've been working on Swift and it's impossible to parse my JSON. I've created the struct with http://www.jsoncafe.com/ , everything looks great, optional values, coding keys, etc. But all the time I get this Error.

Error dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.})))

This is my code.

func fetchData() {
    guard let gitUrl = URL(string: "https://www.zaragoza.es/sede/servicio/farmacia.json?tipo=guardia") else { return }
    URLSession.shared.dataTask(with: gitUrl) { (data, response
        , error) in
        guard let data = data else { return }
        do {
            let decoder = JSONDecoder()
            let guardia = try decoder.decode([Result].self, from: data)
            print(guardia.first?.title as Any)

        } catch let err {
            print("Error", err)
        }
        }.resume()

}

JSON:

    { "totalCount": 12, 
"start": 0,
  "rows": 50,
  "icon": "farmaciaguardia",
  "result": [
    {
      "id": 8747,
      "title": "Farmacia De Miguel Golvano, Cristóbal",
      "telefonos": "976220481",
      "horario": "Lunes a Sábado excepto festivos de 9:30 a 22:00 h",
      "clasificacion": "HorarioAmpliado",
      "calle": "Pº de Sagasta, 13",
      "geometry": {
        "type": "Point",
        "coordinates": [
          -0.8857963286144336,
          41.643332650243835
        ]
      },
      "guardia": {
        "fecha": "2019-04-20T00:00:00Z",
        "turno": "T-05",
        "horario": "Abiertas de 9:15 h. a 9:15 h. del día siguiente",
        "sector": "Sector Centro-Esquina C/ Bolonia"
      },
      "type": [
        "http://www.zaragoza.es/sede/portal/skos/vocab/FarmaciaGuardia/2019-04-20",
        "http://www.zaragoza.es/sede/portal/skos/vocab/FarmaciaHorarioAmpliado"
      ]
    }]}

Finally get it. There is a problem with headers. This is the answer. Thanks a lot.

func fetchData() {

            let url = URL(string: "https://www.zaragoza.es/sede/servicio/farmacia.json?tipo=guardia")
        var request = URLRequest(url: url!)
        request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")  // the request is JSON
        request.setValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept")
        let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
                do {
                    let jsonDecoder = JSONDecoder()
                    let responseModel = try jsonDecoder.decode(Result.self, from: data!)
                    print(responseModel)
                } catch {
                    print("Error: \(error.localizedDescription)")
                }

            }
            task.resume()

    }

You're telling the decoder that your JSON response has a top level element of an array but it doesn't. The array is in a nested property called result. You need to create something like

struct ResultToDecode: Decodable {
   let result: [Result]
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM