我一直在研究Swift,无法解析我的JSON。我已经使用http://www.jsoncafe.com/创建了该结构,所有内容看起来都很不错,可选值,编码键等。但是,每次我都遇到此错误。
错误dataCorrupted(Swift.DecodingError.Context(codingPath:[],debugDescription:“给定的数据不是有效的JSON。”,底层错误:可选(错误域= NSCocoaErrorDomain代码= 3840,“ JSON文本不是以数组或对象和允许未设置片段的选项。“ UserInfo = {NSDebugDescription = JSON文本不是以数组或对象开头,并且不允许设置片段的选项。})))
这是我的代码。
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"
]
}]}
答案 0 :(得分:0)
您告诉解码器您的JSON响应具有数组的顶级元素,但没有。该数组位于称为result的嵌套属性中。您需要创建类似
的内容struct ResultToDecode: Decodable {
let result: [Result]
}
答案 1 :(得分:0)
最后得到它。 标头存在问题。这就是答案。非常感谢。
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()
}